找到sql join失败的值

时间:2011-10-05 15:17:48

标签: mysql sql database

说我有一个查询,例如:

SELECT *
FROM Table_1
JOIN Table_2
ON Table_1.Col_1 = Table_2.Col_1

所以我有100条记录,其中98条是相同的,所以查询将打印出98条中的98条。如何让SQL打印出未能满足连接的2?

4 个答案:

答案 0 :(得分:8)

使用LEFT JOIN

SELECT *
FROM Table_1
LEFT JOIN Table_2 ON (Table_1.Col_1 = Table_2.Col_1)

如果Table_2子句不匹配,ON的字段将为NULL。然后,您就可以添加WHERE TABLE_2.Col_1 IS NULL,仅保留Table_1Table_2内没有匹配项的记录。

答案 1 :(得分:7)

LEFT JOIN的替代方法是使用EXISTS。

SELECT * FROM Table_1
WHERE NOT EXISTS (SELECT * FROM Table_2 WHERE Col_1 = Table_1.Col_1)

答案 2 :(得分:0)

试试这个:

SELECT * FROM `Table_1` LEFT JOIN `Table_2` ON (`Table_1`.`Col_1` = `Table_2`.`Col_1`)

答案 3 :(得分:0)

SELECT *
FROM Table1 AS A
LEFT OUTER JOIN Table2 AS B
ON (A.Col = B.Col)
WHERE B.Col IS NULL