[英]PHP MySQL: Getting rows from table A where values of column Z of Table A not present in column Z of table B
我有2个表格项目和item_relations
项目具有4列row_id(主键),story_id,field1和field2
item_relation存储项目表中每行之间的关系,它具有2列parent_story_id和child_story_id。 两列均存储项目的story_id。
父项可以有许多子项,而子项可以有1个或多个父项。 但是子项不能有自己的子项。
现在,我要从item_relation.child_story_id中不存在items.story_id的项目中选择行
我该怎么做呢?
我想从item_relation.child_story_id中不存在items.story_id的项目中选择行
您可以使用NOT IN,NOT EXISTS或LEFT JOIN / WHERE ... IS NULL。
NOT IN的示例:
SELECT *
FROM items
WHERE items.story_id NOT IN (
SELECT child_story_id FROM item_relation
)
LEFT JOIN / WHERE ...的示例为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
不存在的示例:
SELECT *
FROM items
WHERE NOT EXISTS (
SELECT NULL
FROM item_relation
WHERE item_relation.child_story_id = items.story_id
)
文章NOT IN vs.NOT EXISTS vs.LEFT JOIN / IS NULL: Quassnoi的 MySQL解释了这些技术之间的差异,并比较了它们的性能。 摘要:
这就是为什么在MySQL中搜索缺失值的最佳方法是使用LEFT JOIN / IS NULL或NOT IN而不是NOT EXISTS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.