SQL学习指南第三篇

再谈连接

外连接

之前的范例都是没有考虑条件可能无法为表中的所有行匹配的问题

左外连接与右外连接

SELECT a.account_id, a.cust_id, b.name FROM account a LEFT OUTER JOIN business b ON a.cust_id = b.cust_id;

外连接包括第一个表的所有行,但仅仅包含第二个表中那些匹配行的数据。关键字 left 指出连接左边的表决定结果集的行数,而右边只负责提供与之匹配的列值。因此,如果想要通过表 A 和 B 外连接得到结果为 A 中的所有行和 B 中匹配列的额外数据,则可以指定 A left outer join B 或者 B right outer join A。

三路外连接

SELECT a.account_id, a.product_cd, CONCAT(i.fname, ' ', i.lname) AS person_name, b.name AS business_name
FROM account a LEFT OUTER JOIN individual i ON a.cust_id = i.cust_id
LEFT OUTER JOIN business b ON a.cust_id = b.cust_id;

--利用子查询限制查询中连接的数目
SELECT account_ind.account_id, account_ind.product_cd, account_ind.person_name, b.name AS business_name FROM 
(SELECT a.account_id, a.product_cd, a.cust_id, CONCAT(i.fname, ' ', i.lname) AS person_name FROM account a 
LEFT OUTER JOIN individual i ON a.cust_id = i.cust_id) account_ind LEFT OUTER JOIN business b ON account_ind.cust_id = b.cust_id;

--这两个的结果一样

猜你喜欢

转载自www.cnblogs.com/sunshine21/p/10554921.html