Say I have 2 tables, one called categories and one called cat_pages.
The categories table has columns ID, title and timestamp. For example:
CREATE TABLE categories (
id INT UNSIGNED PRIMARY KEY,
title VARCHAR(32),
`timestamp` TIMESTAMP,
INDEX (title)
) Engine=InnoDB;
The cat_pages has 2 columns, cat_id and page_id:
CREATE TABLE cat_pages (
cat_id INT UNSIGNED
REFERENCES categories (id)
ON DELETE CASCADE ON UPDATE CASCADE,
page_id INT UNSIGNED
REFERENCES pages (id)
ON DELETE CASCADE ON UPDATE CASCADE,
UNIQUE INDEX (cat_id, page_id),
INDEX (page_id, cat_id),
) Engine=InnoDB;
I'm trying to join the categories table with the cat_pages table on the ID, such that
- Only categories with id's in the category_pages table are retrieved and
- Each category is only displayed once in the resultset
The query:
SELECT * FROM categories as c
LEFT JOIN cat_pages as p ON c.id = p.cat_id
produces a result set that has the categories repeated multiple times (as there are multiple matches in the cat_pages table. What do I need so that each category is only shown once, and not at all if there are no matches in the cat_pages table?