我有这些MySQL表:
表1:
id | writer
1 | Bob
2 | Marley
3 | Michael
表2:
user_one | user_two
1 | 2
这个查询:
SELECT table1.id FROM table1 LEFT JOIN table2 ON table1.id = table2.user_one
此查询将返回table1的所有行,即1,2,3
我想只选择左关节中找不到的行。所以它应该只返回标识为3
我希望与INNER JOIN相反,它只会选择在连接中找到的行。如果左边的连接存在,如何得到反面,忽略它并移动到下一行。希望我明白
答案 0 :(得分:39)
您可以使用以下查询:
SELECT table1.id
FROM table1
LEFT JOIN table2
ON table1.id IN (table2.user_one, table2.user_two)
WHERE table2.user_one IS NULL;
虽然,根据table2
上的索引,您可能会发现两个联接的效果更好:
SELECT table1.id
FROM table1
LEFT JOIN table2 AS t1
ON table1.id = t1.user_one
LEFT JOIN table2 AS t2
ON table1.id = t2.user_two
WHERE t1.user_one IS NULL
AND t2.user_two IS NULL;
答案 1 :(得分:11)
如果您不想从table2
返回任何列,最好的方法之一就是使用NOT EXISTS
SELECT table1.id
FROM table1 T1
WHERE
NOT EXISTS (SELECT *
FROM table2 T2
WHERE T1.id = T2.user_one
OR T1.id = T2.user_two)
在语义上,这表示您要查询的内容:选择第二个表中没有匹配记录的每一行。
MySQL针对EXISTS
进行了优化:它会在找到第一个匹配记录后立即返回。
答案 2 :(得分:3)
以下是一个查询,该查询仅返回user_one
的{{1}}和user_two
列中未找到对应关系的行:
table2
每列(SELECT T1.*
FROM table1 T1
LEFT OUTER JOIN table2 T2A ON T2A.user_one = T1.id
LEFT OUTER JOIN table2 T2B ON T2B.user_two = T1.id
WHERE T2A.user_one IS NULL
AND T2B.user_two IS NULL
和user_one
)都有一个关节,查询只返回没有匹配关节的行。
希望这会对你有所帮助。
答案 3 :(得分:2)
尝试:
SELECT A.id FROM
(
SELECT table1.id FROM table1
LEFT JOIN table2 ON table1.id = table2.user_one
WHERE table2.user_one IS NULL
) A
JOIN (
SELECT table1.id FROM table1
LEFT JOIN table2 ON table1.id = table2.user_two
WHERE table2.user_two IS NULL
) B
ON A.id = B.id
参见 Demo
或者你可以使用两个LEFT JOINS
和别名,如:
SELECT table1.id FROM table1
LEFT JOIN table2 A ON table1.id = A.user_one
LEFT JOIN table2 B ON table1.id = B.user_two
WHERE A.user_one IS NULL
AND B.user_two IS NULL
参见 2nd Demo
答案 4 :(得分:1)
尝试以下查询: -
SELECT table1.id
FROM table1
where table1.id
NOT IN (SELECT user_one
FROM Table2
UNION
SELECT user_two
FROM Table2)
希望这会对你有所帮助。
答案 5 :(得分:1)
SELECT table1.id
FROM table1
LEFT JOIN table2 ON table1.id = table2.user_one
WHERE table2.user_one is NULL