| 知乎专栏 |
查询两个表,产生交集的数据,初学者很容易犯的错误。
SELECT
COUNT(n1_0.id)
FROM
notification n1_0,
notification_status ns1_0
WHERE
n1_0.id <> ns1_0.notification_id
正确的做法是使用 LEFT OUTER JOIN
SELECT
COUNT(n1_0.id)
FROM
notification n1_0 LEFT OUTER JOIN notification_status ns1_0 ON n1_0.id<>ns1_0.notification_id;
LEFT JOIN 关键字从左侧表返回所有的行,即使右侧表中没有匹配。如果右侧表中没有匹配,则结果为 NULL。
根据两个或多个表中的列之间的关系,从这些表中查询数据。
举例
SELECT
*
FROM
notification n
LEFT JOIN
notification_status ns ON n.id = ns.notification_id
WHERE
ns.notification_id IS NOT NULL;
使用 JOIN 替代 LEFT JOIN
SELECT
*
FROM
notification n
JOIN
notification_status ns ON n.id = ns.notification_id;
SELECT
*
FROM
notification n
INNER JOIN
notification_status ns ON n.id = ns.notification_id;