码迷,mamicode.com
首页 > 数据库 > 详细

数据库---查询语句(三):高级查询

时间:2016-01-17 23:02:07      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

高级查询

一.多表连接(连接的是两个表中的列)

1.select * from Info,Nation where Info.Nation=Nation.Code

 select  Info.Code,Info.Name,Nation.Name  from Info ,Nation where Info.Nation=Nation.Code    //where 后面是一个外键关系

 select * from Info      出现的现象,形成的表叫做笛卡尔积

2. join 连接

 select * from Info join Nation  on  Info.Nation=Nation.Code    (join on 语法   on 后面跟条件)       //join 也可能会形成笛卡尔积,大数据不建议用

二.多表联合(扩展行)

select * from  Info  where Code=‘p001‘

select * from Info where Nation=‘n001‘

两条结果放到一起→用union连接:

select * from Info  where Code=‘p001‘ union select * from Info where Nation=‘n001‘

注:多表联合有个要求--查询的列数要求一样

三.子查询:无关子查询

(有两个查询语句,其中一个查询的结果被另一个用,那么被用的查询叫做子查询,用的那个查询叫做附查询)

1. select Code  from  Nation  where  Name=‘汉族‘

    select * from Info where  Nation=‘n001‘

    → →select * from Info where  Nation=(select Code from Nation where Name=‘汉族‘)    

     //括号里面的查询结果,当做外面查询的条件,所以里面的查询叫做子查询(也叫里层查询),外面的查询叫做复查询(也叫外层查询)

    //上面的信息如果要除了这条数据之外,其他的数据,可以用“ != ”

2. select * from Info where Nation in (select Code  from Nation where Name=‘汉族‘ or Name=‘苗族‘)

     //子查询查的不是一条数据,而是多条数据的话,用in 链接

3. select * from Info where Nation not in (select Code  from Nation where Name=‘汉族‘ or Name=‘苗族‘)

    //不要这两条数据

四.子查询:相关子查询(里层查询需要用到外层查询的条件)

  select * from Car a  where a.Oil <(select avg(Oil) from Car b where b.Brand = a.Brand) 

(括号里相当于--select * avg (oil) from car where brand=‘b001‘)

 

数据库---查询语句(三):高级查询

标签:

原文地址:http://www.cnblogs.com/supermeimei/p/5137855.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!