我想从表a中得到行,唯一的\u键列在表b中,同时,唯一的\u键在表c中不存在。所以如果我写表格,
table a
+----+------+-----------+
| id | Name | int_value |
+----+------+-----------+
| a1 | aa | 1 |
| a2 | bb | 2 |
| a3 | cc | 5 |
+----+------+-----------+
table b
+----+------+-----------+
| id | Name |unique_key |
+----+------+-----------+
| a1 | aa | u1 |
| a2 | bb | u2 |
| a3 | cc | u5 |
+----+------+-----------+
table c
+----+------+-----------+
| id | Name |unique_key |
+----+------+-----------+
| c1 | aa | u1 |
| c2 | bb | u2 |
| c3 | cc | u3 |
+----+------+-----------+
因此,我想
id name int_value b.unique_key
a3 cc 5 u5
因为表c中不存在u5。我尝试了这些sql,但都没有得到正确的结果。你会怎么做?
SELECT a.*, b.unique_key
FROM a
LEFT JOIN ( SELECT id FROM b ) b
ON a.id = b.id
LEFT JOIN ( SELECT unique_key FROM c ) c
ON b.unique_key <> c.unique_key;
SELECT a.*, b.unique_key, c.unique_key
FROM a
LEFT JOIN ( SELECT id FROM b ) b
ON a.id = b.id
LEFT JOIN ( SELECT unique_key FROM c ) c
ON b.unique_key = c.unique_key
WHERE c.unique_key IS NULL;
3条答案
按热度按时间9gm1akwq1#
你可以在下面试试-
演示
输出:
wj8zmpe12#
你可以用
NOT EXISTS
具体如下:xoefb8l83#
另一种方法是使用not in
结果
id: a3, name: cc, int_value: 5, unique_key: u5