【问题标题】:PHP MySQL: Getting rows from table A where values of column Z of Table A not present in column Z of table BPHP MySQL:从表 A 中获取行,其中表 A 的列 Z 的值不存在于表 B 的列 Z
【发布时间】:2010-07-21 20:00:08
【问题描述】:

我有 2 个表项和 item_relations

items 有 4 列 row_id(主键)、story_id、field1 和 field2

item_relation 将每行之间的关系存储在 items 表中,它有 2 列 parent_story_id 和 child_story_id。两列都存储来自项目的 story_id 行。

一个父项可以有许多子项,而一个子项可以有 1 个或多个父项。但子项不能有自己的子项。

现在我想从 item_relation.child_story_id 中不存在 items.story_id 的项目中选择行

我该怎么做?

【问题讨论】:

    标签: php mysql mysqli


    【解决方案1】:

    我想从 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 ... 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
    

    不存在的例子:

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

    Quassnoi 的文章NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL: MySQL 解释了这些技术之间的差异并比较了它们的性能。总结:

    这就是为什么在 MySQL 中搜索缺失值的最佳方法是使用 LEFT JOIN / IS NULL 或 NOT IN 而不是 NOT EXISTS。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-04
      • 1970-01-01
      • 2011-01-28
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      • 2016-12-07
      相关资源
      最近更新 更多