21

MySQL- 技术专题 - 连接查询和子查询

 3 years ago
source link: https://xie.infoq.cn/article/e5ec15bfab8c19f87e670e46a
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

思维导图:

YbmeIrF.png!mobile

连接查询是将两个或者两个以上的表连接起来,从中选取所需要的数据;

连接查询是关系数据库中最主要的查询。

一、内连接查询

可以查询两个或两个以上的表

1.查询两个表的所有数据,以笛卡尔积的形式展现出来

SELECT * FROM 表1,表2;

例如:查询t_book表和t_booktype表的内容:

select * from t_book;

vAvQzaU.png!mobile

有5种字段,4条数据;

select * from t_booktype;

6fequa2.png!mobile

有2种字段,3条数据;

而查看两个结合表的数据,则用:

select * from t_book,t_booktype;

3u6bu2u.png!mobile

总共有12条数据,7种字段;

2.将两张表的数据合成一张表(字段结合)

例如,之前查询到t_book表中的内容是:

vAvQzaU.png!mobile

如果想要在此表中加上t_booktype字段的话,就要用内连接:

select * from t_book,t_booktype where t_book.bookTypeId=t_booktype.id;

去掉bookTypeId和id字段,则有:

select bookName,price,author,bookTypeName from t_book,t_booktype where t_book.bookTypeId=t_booktype.id;

当然,这样效果不是很好,读者很难区分bookTypeName到底是t_book表中还是t_bookType表中的字段;

这时,可以给两个表取别名,给t_book表取别名tb,给t_booktype表取别名tby,则有:

select tb.bookName,tb.price,tb.author,tby.bookTypeName from t_book tb,t_booktype tby where tb.bookTypeId=tby.id;

fQFzm2j.png!mobile

结果是一样的,但是可以看出哪个表对应的哪个字段;

二、外连接查询

外连接查询可以查出一张表的所有信息

SELECT * FROM 表名1 LEFE|RIGHT JOIN 表名2 ON 表名1.属性1=表名2.属性2;

1.左连接查询:

可以查出表1的所有记录,而表2只能查出匹配的记录;

例如:查出表1的所有记录,加上表2的bookTypeName字段:

select * from t_book left join t_bookType on t_book.Id=t_bookTypeId.id;

JNRrMre.png!mobile

看到t_book表的所有记录都有,且id为4的记录在t_bookType表中并没有与之对应的,因此为null;

2.右连接查询:

可以查出表2的所有记录,而表1只能查出匹配的记录;

例如:查出表2的所有记录,加上表1的字段:

select * from t_book left join t_bookType on t_book.Id=t_bookTypeId.id;

6jE7vuz.png!mobile

可以看到t_bookType表的内容都查出来了,且bookypeName为3的记录在t_book表中没有记录对应,因此为null;

三、子查询

1.带IN关键字的子查询

若要查询bookTypeId在t_booktype表中的数据:

select * from t_book where bookTypeId in (select id from t_booktype);

jY7rmm.png!mobile

可以看出没有bookTypeId等于4的这条数据,因为bookTypeId等于4不在t_booktype表中;

若要查询bookTypeId不在t_booktype表中的数据:

select * from t_book where bookTypeId not in (select id from t_booktype);

veEfEbz.png!mobile

可以看出查到了booTypeId等于4的这条不在t_booktype表中的数据;

2.带比较运算符的子查询

先查看t_pricelevel表内容:select * from t_pricelevel;

YbArqiy.png!mobile

查看price=80的书籍:

select * from t_book where price >=(select price from t_pricelevel where priceLevel = 1);

ZFfMRrI.png!mobile

3.带exist关键字查询

例如:如果t_booktype表存在,才需要继续查询t_book表;

select * from t_book where exists (select * from t_booktype);

iQVnQzr.png!mobile

当然,也有not exists,在前面加上NOT即可;

4.带any的关键字子查询

例如:查询t_book表中price任何一个大于t_pricelevel表中price的数据:

select * from t_book where price > any (select price from t_pricelevel where priceLevel );

zuIjUbv.png!mobile

可以看出t_book表中price=24的数据并没有查出来;

5.带all的关键字查询

select * from t_book where price> all (select price from t_pricelevel);

nEnQre.png!mobile

t_book表中只有两条数据大于t_pricelevel表中最大的价格80;


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK