【问题标题】:mysql find records in a table that reference records that don't existmysql 在表中查找引用不存在的记录的记录
【发布时间】:2015-02-08 12:59:46
【问题描述】:

在 mysql 中,如果我有一条记录引用了另一条记录的 id。例如

Table 1
id          bigint
tabe2ref    bigint

Table 2
id          bigint

table2ref 仅引用 Table2.id。
有没有办法列出表 1 中引用表 2 中不存在该记录的记录的所有记录?

【问题讨论】:

    标签: mysql


    【解决方案1】:

    如果您还想要 table2 中的数据,请使用 LEFT JOIN,如 dognose 的回答。如果您只想要 table1 中的数据,请使用子查询,如下所示:

    SELECT * FROM table1 WHERE table2ref NOT IN (
        SELECT id FROM table2
    )
    

    基本上,这读作“从表 1 中获取所有内容并减去所有具有 table2ref 的行,但该行不在 table2 的所有行中。”

    【讨论】:

      【解决方案2】:

      您正在寻找 LEFT JOIN - 表 2 中的条目不存在的所有内容在加入后将具有 table2.idnull

      SELECT 
          table1.id, table1.table2ref, table2.id 
      FROM  
          table1 
      LEFT JOIN 
          table2 
      ON 
          table1.table2ref = table2.id
      WHERE
         ISNULL(table2.id) -- only those records with missing reference.
      

      另见:http://giannopoulos.net/wp-content/uploads/2013/05/BHVicYICMAAdHGv.jpg (第一列,第二行)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-09
        • 2014-06-26
        • 2014-01-19
        • 2012-12-24
        • 2010-10-25
        • 1970-01-01
        相关资源
        最近更新 更多