MySQL 子查询

1、where型的子查询

where型的子查询就是把内层查询的结果当作外层查询的条件。

--(1) 查询与27号运动 同一性别,同一城市的其他人

-- 第一步 查询27号球员的性别、城市
select sex,town from players where playno=27;
-- 第二步 将查询的结果放置where条件处
select playerno,sex,town from players 
where (sex,town) = (select sex,town from players where playerno= 27);


--(2)获取和27号球员出生在同一年的球员号码

--第一步 查询27号球员的出生年
select year(birth_date)from players where playerno =27;
-- 第二步 将查询的结果放置where条件处
select playerno,birth_date from players 
where year(birth_date)=(select year(birth_date)from players where playerno =27);

 

2、from型的子查询

from子查询就是把子查询的结果(内存里的一张表)当作一张临时表,然后再对它进行处理。

-- 获取编号小于10的男性球员号码
--普通写法: 
select*from players where sex = "m" and playerno <10;
--子查询写法
select*FROM (select *from players where playerno < 10) AS A WHERE SEX="M";

 

3、列 子查询

列子查询就是把返回一列的值,因此就不能用 = > < 等符号

配合以下条件符使用:

  • in 在指定项里
  • any 在子查询任何返回结果比较
  • all 在子查询所有返回结果比较
--(in 举例) 获取球员性别为女的所有球员的球号、名字及城市

-- 普通写法
select playerno,name,town from players where sex="f";
-- in 列子查询写法
select playerno,name,town from players 
where playerno in(select playerno from players where sex="f");

-- (any 举例)获取至少比同城另一位球员年轻的所有球员号码、生日、城市
select playerno,birth_date,town from players as p1
where birth_date > any(select birth_date from players as p2 where p1.town=p2.town)

--(all 举例)获取最老的球员的号码、名字和生日
--普通写法
select playerno,name,min(birth_date)from players;
-- all 列子查询写法
select playerno,name,birth_date from players where birth_date<= all(select birth_date from players);

 

4、exists 子查询

只要子句中至少返回一个值,则exists 语句就返回TRUE

-- (exists 举例)获取哪些至少支付了一次返款的球员姓名和首字母
select NAME,initials from players 
where exists
(select*from penalties where penalties.playerno=players.playerno);

-- (exists 举例)获取哪些从来没有付过罚款的球员姓名和首字母
select NAME,initials from players 
where  not exists
(select*from penalties where penalties.playerno =players.playerno);

 

posted @ 2017-11-27 14:40  JennyYIN  阅读(372)  评论(0编辑  收藏  举报