1. 程式人生 > >MySql資料庫查詢(四)——子查詢

MySql資料庫查詢(四)——子查詢

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;