MySql数据库查询(四)——子查询

版权声明:此账号的博客均为原创,侵权必究! https://blog.csdn.net/qq_37084904/article/details/83019916

1.带IN关键字的子查询

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

select * from t_book;

select * from t_booktype;

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

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

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

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

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

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

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

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

查看price=80的书籍:

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

3.带exist关键字查询

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

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

当然,也有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 );

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

5.带all的关键字查询

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

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

猜你喜欢

转载自blog.csdn.net/qq_37084904/article/details/83019916