SELECT NOT IN来自其他表的两个外键

时间:2016-09-28 09:47:29

标签: mysql database

我正在尝试查找返回tableB上不存在的所有 tableA.tba_id SELECT查询(请注意,这是两个不同的外键 - tbb_tbAID1 tbb_tbAID2 You can find DB Model here

到目前为止我能做什么
这仅测试一列

SELECT tba_id FROM tableA 
WHERE tba_id NOT IN
  (SELECT tbb_tbAID1 FROM tableB
  WHERE tbb_date > '$date2')

尝试在两个外键上测试时出现MySQL错误

  

1241 - 操作数应包含1列

查询:

SELECT tba_id FROM tableA 
WHERE tba_id NOT IN
  (SELECT tbb_tbAID1,tbb_tbAID2 FROM tableB
  WHERE tbb_date > '$date2')

尝试2:

SELECT tba_id FROM tableA 
WHERE tba_id NOT EXISTS
    (SELECT 1 FROM tableB
    WHERE (tba_id = tbb_tbAID1 OR tba_id = tbb_tbAID2)
  AND tbb_date > '$date2')

但是比第一次尝试获得的结果更多(这表明它做得非常错误)

Try3:

SELECT tba_id FROM tableA JOIN tableB ON tba_id!=tbb_tbAID1 AND tba_is!=tbb_tbAID2 WHERE tbb_data > '$data'

这导致了大量的数据,远离第一种方法。

2 个答案:

答案 0 :(得分:0)

进行连接而不是嵌套查询,它也更快,更高效。

SELECT tba_id FROM tableA JOIN tableB ON tba_id!=tbb_tbAID1 AND tba_is!=tbb_tbAID2

答案 1 :(得分:0)

实际工作的查询:

SELECT tba_id FROM tableA
WHERE NOT EXISTS (SELECT * FROM tableB WHERE (tba_id = tbb_tbAID1 OR tba_id = tbb_tbAID2) AND tbb_data > '$date')

Try2 上,我将SELECT 1替换为SELECT *并删除了WHERE tba_id NOT EXISTS并像魅力一样工作。