Mysql之联合查询那些事儿

联合查询之union
union可以合并两个以上 select语句查询出来的表,并消除表中的重复行。
【Mysql之联合查询那些事儿】其中,select语句需要拥有相同数量和相同数据类型的列。

  1. 查询中国各省的ID以及省份名称
    select ProID,ProName from T_Province
    复制代码
  2. 湖南省所有地级市ID、名字
    select CityID,CityName from T_City
    where ProID = (
    select ProID from T_Province where ProName="湖南省"
    );
    复制代码
  3. 用union将他们合并
    select ProID,ProName from T_Province
    union
    select CityID,CityName from T_City
    where ProID = (
    select ProID from T_Province where ProName="湖南省"
    );
    复制代码
    这样就得到两个查询结果的并集了。
UNION 合并后的集合中的列名总是等于 UNION 中第一个 SELECT 语句中的列名。
联合查询之union all
select ProID,ProName from T_Province
union all
select CityID,CityName from T_City
where ProID = (
select ProID from T_Province where ProName="湖南省"

);
复制代码
当使用union all,不会消除重复行。
联合查询之inner join
  1. 查询湖北省有多少地级市
    不用联合查询:
select count(CityID) from T_City
where ProID = (select ProID from T_Province where ProName="湖北省")
复制代码
通过ProID将两张表连接在一起
select ProName,CityName from(
T_City join T_Province on T_City.ProID = T_Province.ProID


where ProName="湖北省"
复制代码
  1. 统计各省地级市的数量,输出省名、地级市数量
    select T_City.ProID,ProName,count(CityID) as cc from(
    T_City join T_Province
    on T_City.ProID = T_Province.ProID
    )
    group by T_City.ProID
    order by cc desc;
    复制代码
    什么的select语句中要输出的ProID应该是T_City和T_Province中的一个,不然就会报错。
两个表之间需要有共同的(列名不一定相同)“语言”才能join。
可以给表起个别名,将T_City表的别名设为tc,将T_Province的别名设为tp。
select tc.ProID,ProName,count(CityID) as cc from(
T_City tc join T_Province tp on T_City.ProID = T_Province.ProID

)
group by tc.ProID
order by cc desc;
复制代码
  1. 查询拥有20个以上区县的城市,输出城市名,区县数量
    select CityName,count(DisName) disCount from (
    T_City tc join T_District td
    on tc.CityID = td.CityID
    )
    group by CityName
    having disCount > 20;
    复制代码
    联合查询之三表联合
  2. 区县最多的3个城市是哪个省的哪个市,查询结果包括省名,市名,区县数量
    select tp.ProName,tcd.CityName,tcd.ci from
    (
    select ProID,CityName,count(ID) ci from(T_City tc join T_District td on tc.CityID = td.CityID)
group by tc.CityID
order by ci desc
limit 3
)tcd
join T_Province tp on tcd.ProID = tp.ProID;
复制代码
联合查询之left join&right join
内连接是基于左右两表公共的部分
左连接是基于左右两表公共的部分加上左表特有的部分
右连接是基于左右两表公共的部分加上右表特有的部分
查询所有省份和它的城市信息
select * from(
T_Province tp join T_City tc
on tp.ProID = tc.ProID
);
复制代码
查询所有省份和它的城市信息和没有城市的省份信息
select * from(
T_Province tp left join T_City tc
on tp.ProID = tc.ProID
);
复制代码
查询所有省份和它的城市信息和没有省份的城市信息
select * from(
T_Province tp right join T_City tc
on tp.ProID = tc.ProID
);
复制代码
如果你觉得这篇文章对你有点用的话,麻烦请给我们的开源项目点点star: http://github.crmeb.net/u/defu 不胜感激 !

    推荐阅读