MySQL中几种联合查询的介绍(left/right/inner join)教程SQL

印迹发布于:2019-3-27 1070

以下主要介绍了LEFT JOIN 关键字会从左表 (table_name1) 那里返回所有的行,即使在右表 (table_name2) 中没有匹配的行。

表a 

aidadate
1a1
2a2
3a3

表b 

bidbdate
1b1
2b2
3b3

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

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

这是仅取出匹配的数据。

此时的取出的是:

1a1b1
2a2b2

那么left join 指:

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

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

此时的取出的是:

1a1b1
2a2b2
3a3空字符

同样的也有right join

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

此时的取出的是:

1a1b1
2a2b2
4空字符b4

LEFT JOIN 或 LEFT OUTER JOIN。

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

实例
"Persons" 表:
Id_PLastNameFirstNameAddressCity
1AdamsJohnOxford StreetLondon
2BushGeorgeFifth AvenueNew York
3CarterThomasChangan StreetBeijing
"Orders" 表:
Id_OOrderNoId_P
1778953
2446783
3224561
4245621
53476465
左连接(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

结果集:

LastNameFirstNameOrderNo
AdamsJohn22456
AdamsJohn24562
CarterThomas77895
CarterThomas44678
BushGeorge

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

其它示例

创建a表及b表:

create table a ( id int not null auto_increment primary,name char(20),sex char(8),age tinyint(3) ,tel char(13),beizhu text);
create table b (id int not null auto_increment primary,title char(20),content text,uid int(10));

显示所有有关联的信息:

select * from a inner join b on a.id=b.uid;

显示b.uid为2的所有信息:

select a.id,a.name,b.title,b.uid from a inner join b on a.id=b.uid where uid=2;



http://www.virplus.com/thread-233.htm
转载请注明:2019-3-27 于 VirPlus 发表

推荐阅读
最新回复 (0)

    ( 登录 ) 后,可以发表评论!

    返回