Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

62.2. JOIN

62.2.1. LEFT JOIN / LEFT OUTER JOIN

查询两个表,产生交集的数据,初学者很容易犯的错误。

		
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。

62.2.2. JOIN / INNER JOIN

根据两个或多个表中的列之间的关系,从这些表中查询数据。

举例

			
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;