sql查询获取带条件的行

pod7payv  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(309)

我想从表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;
9gm1akwq

9gm1akwq1#

你可以在下面试试-
演示

SELECT a.*, b.unique_key
FROM a JOIN b 
ON a.id = b.id
LEFT JOIN c 
ON b.unique_key = c.unique_key
where c.unique_key is null

输出:

id  Name    int_value   unique_key
a3  cc       5           u5
wj8zmpe1

wj8zmpe12#

你可以用 NOT EXISTS 具体如下:

SELECT a.*, b.unique_key
FROM a JOIN  b
ON a.id = b.id
WHERE NOT EXISTS (SELECT 1 FROM c 
                 WHERE b.unique_key = c.unique_key);
xoefb8l8

xoefb8l83#

另一种方法是使用not in

SELECT a.id, a.name, a.int_value, b.unique_key
FROM a
JOIN b ON a.id = b.id
WHERE b.unique_key NOT IN (SELECT DISTINCT c.unique_key FROM c)

结果 id: a3, name: cc, int_value: 5, unique_key: u5

相关问题