我有这些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
我只想选择在左关节中找不到的行。所以它应该只返回ID为ID的行3
3
我想要与INNER JOIN相反,它将仅选择在联接中找到的行。如何获得相反的结果(例如是否存在左联接),忽略它并移至下一行。希望我明白
您可以使用以下查询:
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您可能会发现两个联接的性能更好:
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;