views:

25

answers:

1

I have 2 tables items and item_relations

items has 4 columns row_id(primary key), story_id, field1 and field2

item_relation stores the relation between each rows in items table it has 2 columns parent_story_id and child_story_id. Both columns store story_id's of rows from items.

A parent item can have many child items and a Child can have 1 or more parent items. but a child item cannot have its own child items.

Now I want to SELECT rows from items for which items.story_id is not present in item_relation.child_story_id

How do I go about doing this?

+3  A: 

I want to SELECT rows from items for which items.story_id is not present in item_relation.child_story_id

You could use NOT IN, NOT EXISTS or LEFT JOIN/WHERE ... IS NULL.

An example with NOT IN:

SELECT *
FROM items
WHERE items.story_id NOT IN (
    SELECT child_story_id FROM item_relation
)

An example with LEFT JOIN/WHERE ... IS NULL:

SELECT items.*
FROM items
LEFT JOIN item_relation
ON items.story_id = item_relation.child_story_id
WHERE item_relation.child_story_id IS NULL

An example with NOT EXISTS:

SELECT *
FROM items
WHERE NOT EXISTS (
    SELECT NULL
    FROM item_relation
    WHERE item_relation.child_story_id = items.story_id
)

The article NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL: MySQL by Quassnoi explains the differences between these techniques and compares their performance. The summary:

That’s why the best way to search for missing values in MySQL is using a LEFT JOIN / IS NULL or NOT IN rather than NOT EXISTS.

Mark Byers