Home > Database > Mysql Tutorial > body text

对MySQL几种联合查询的通俗解释

WBOY
Release: 2016-06-07 16:28:46
Original
809 people have browsed it

表a aid adate 1 a1 2 a2 3 a3 表b bid bdate 1 b1 2 b2 4 b4 两个表a、b相连接,要取出id相同的字段。 select * from a inner join b on a.aid = b.bid 这是仅取出匹配的数据。 此时的取出的是: 1 a1 b1 2 a2 b2 那么left join 指: select * from a left jo

表a

aid adate 
1 a1 
2 a2 
3 a3 
Copy after login

表b

bid bdate 
1 b1 
2 b2 
4 b4 
Copy after login

两个表a、b相连接,要取出id相同的字段。

select * from a inner join b on a.aid = b.bid
Copy after login

这是仅取出匹配的数据。

此时的取出的是:

1 a1 b1 
2 a2 b2 
Copy after login

那么left join 指:

select * from a left join b on a.aid = b.bid 
Copy after login

首先取出a表中所有数据,然后再加上与a、b匹配的的数据。

此时的取出的是:

1 a1 b1 
2 a2 b2 
3 a3 空字符
Copy after login

同样的也有right join

指的是首先取出b表中所有数据,然后再加上与a、b匹配的的数据。

此时的取出的是:

1 a1 b1 
2 a2 b2 
4 空字符 b4
Copy after login

LEFT JOIN 或 LEFT OUTER JOIN。

左向外联接的结果集包括 LEFT OUTER 子句中指定的左表的所有行,而不仅仅是联接列所匹配的行。如果左表的某行在右表中没有匹配行,则在相关联的结果集行中右表的所有选择列表列均为空值。

实例

"Persons" 表:

Id_P LastName FirstName Address City
1 Adams John Oxford Street London
2 Bush George Fifth Avenue New York
3 Carter Thomas Changan Street Beijing

"Orders" 表:

Id_O OrderNo Id_P
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 65

左连接(LEFT JOIN)实例

现在,我们希望列出所有的人,以及他们的定购 - 如果有的话。

您可以使用下面的 SELECT 语句:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
LEFT JOIN Orders
ON Persons.Id_P=Orders.Id_P
ORDER BY Persons.LastName
Copy after login

结果集:

LastName FirstName OrderNo
Adams John 22456
Adams John 24562
Carter Thomas 77895
Carter Thomas 44678
Bush George

LEFT JOIN 关键字会从左表 (Persons) 那里返回所有的行,即使在右表 (Orders) 中没有匹配的行。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!