高级查询

高级查询

  联合查询

  select 列名,列名 from 表名

  union

  select 列名,列名 from 表名

  union:联合,列数一致

  代码:

  

select code,name from info
union
select code,name from nation

  示例:

  


  连接查询

  会形成笛卡儿积

  select * from 表名,表名 where 表名.列名=表名.列名

  如果有列名相同则:表名.列名

  如果没有相同的列名则:列名

  方法一:select 表名.列名,表名.列名,列名,表名.列名 from 表名,表名 where 表名.列名=表名.列名

  方法二:select 表名.列名,表名.列名,列名,表名.列名 from 表名 join left 表名 on 表名.列名=表名.列名

  left:自动补空左表

  right:自动补空右表

  代码:

  

select info.code,info.name,sex,nation.name,birthday from info,nation where info.nation=nation.code
select info.code,info.name,sex,nation.name,birthday from info join nation on info.nation=nation.code

  示例:

  


  子查询

  子查询的结果作为父查询的条件使用

  无关子查询

  子查询和父查询没有关系,子查询单独拿出来可以执行

  1.查找民族为“汉族”的所有人员信息

  

select * from info where nation=(select code from nation where name ='汉族')

  

  2.查询所有厂商时“一汽大众”的汽车信息

  

select * from car where brand in(select brand_code from brand where Prod_code in(select prod_code   from productor where prod_name='一汽大众'))

 

  相关子查询

  1.查询油耗低于该系列平均油耗的汽车信息

  因为外层和里层都有car 所以给他们一个 编号:a.b

  

select * from car a where oil<=(select avg (oil) from car b where b.brand =a.brand)

  

原文地址:https://www.cnblogs.com/Whitehat/p/8258922.html