开发者

PHP MySQL: Getting rows from table A where values of column Z of Table A not present in column Z of table B

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜