我是MySQL的新手,所以我将用一个例子来揭露我的问题...
我有两张桌子:
表1:
+----+-----+-----+-----+-----+
| id | a1 | b1 | c1 | d1 |
+----+-----+-----+-----+-----+
| 1 | ... | ... | ... | ... |
| 2 | ... | ... | ... | ... |
| 3 | ... | ... | ... | ... |
| 4 | ... | ... | ... | ... |
| 5 | ... | ... | ... | ... |
| 6 | ... | ... | ... | ... |
+----+-----+-----+-----+-----+
表2:
+----+-----+-----+-----+---------------+
| id | a2 | b2 | c2 | table1_row_id |
+----+-----+-----+-----+---------------+
| 1 | ... | ... | ... | ... |
| 2 | ... | ... | ... | 4 |
| 3 | ... | ... | ... | ... |
+----+-----+-----+-----+---------------+
表2列table1_row_id
是table1的关键。
我应该使用哪种查询来检索table2.table1_row_id
列中未引用的table1数据?
例如,对于上面的表,查询应返回如下表:
+----+-----+-----+-----+-----+
| id | a1 | b1 | c1 | d1 |
+----+-----+-----+-----+-----+
| 1 | ... | ... | ... | ... |
| 2 | ... | ... | ... | ... |
| 3 | ... | ... | ... | ... |
| 5 | ... | ... | ... | ... |
| 6 | ... | ... | ... | ... |
+----+-----+-----+-----+-----+
可能这很简单,但我不知道该怎么办......
答案 0 :(得分:3)
SELECT *
FROM t1
WHERE
`id` NOT IN (SELECT `table1_row_id`
FROM t2
WHERE
`table1_row_id` IS NOT NULL)
答案 1 :(得分:1)
select t1.a1, t1.b1, t1.c1, t1.d1
from table1 t1
left join table2 t2 on t2.table1_row_id = t1.id
where t2.id is null