08-多表查询

2019-01-06  本文已影响0人  喝酸奶要舔盖__

默认多表查询

select * from stuinfo, stugrade;

示例二:
union: 将多个select语句的结果集纵向结合在一起
union格式:
select 字段 from 表1 union select 字段 from 表2;
select id,name from stuinfo union select id,score from stugrade;

union注意点:
- union两边的select语句字段的个数必须一致
select id,name from stuinfo union select score from stugrade; #报错
- union两边的select语句字段名称可以不一样
select id,name from stuinfo union select id,score from stugrade;
- union两边的select语句字段类型可以不一样
- union结果集字段的名称默认是左边select语句指定的字段名称
- union结果集会自动去重

表的连接

内连接 inner join
示例一:
select * from stuinfo, stugrade where stuinfo.id=stugrade.stuid;
select * from stuinfo inner join stugrade on stuinfo.id=stugrade.stuid;
外连接
select * from stuinfo left join stugrade on stuinfo.id=stugrade.stuid;
select * from stuinfo right join stugrade on stuinfo.id=stugrade.stuid;
select * from stuinfo cross join stugrade; #返回笛卡尔集
select * from stuinfo cross join stugrade on stuinfo.id=stugrade.stuid;
自然连接
select 字段 from 表1 inner join 表2 on 表1.公共字段=表2.公共字段
select 字段 from 表1 natural join 表2;
select * from stuinfo natural join stugrade;
3.1自然左外连接
 select 字段 from 表1 natural left join 表2;
 select * from stuinfo natural left join stugrade;

 3.2自然右外连接
 select 字段 from 表1 natural right join 表2;
 select * from stuinfo natural right join stugrade;
 注意点:
 如果没有同名的字段, 那么返回笛卡尔集
 会对返回的结果集的字段进行优化, 取出重复的连接条件字段

 select * from stuinfo inner join stugrade on stuinfo.stuid=stugrade.stuid;
 select * from stuinfo natural join stugrade;
using() 指定连接字段
 如果连接条件的字段名称一致, 除了可以使用自然连接来简化代码以外还可以使用using来指定连接字段, 两者达到的效果是相同的

 select * from stuinfo inner join stugrade on stuinfo.stuid=stugrade.stuid;
 select * from stuinfo inner join stugrade using(stuid);

子查询

圆括号中的select我们称之为子查询, 圆括号外面的select我们称之为父查询
select 语句 where 条件 (select 语句);
示例一:
查询出成绩是100的人的姓名
select name from stuinfo;
select name from stuinfo where stuid=(select stuid from stugrade where score=100);
# 标准子查询
# 标准子查询的特点: 返回的结果只有一个

示例二: 如果返回值不止一个, 需要使用in | not in
查询出成绩是90分以上人的姓名
select name from stuinfo where stuid in (select stuid from stugrade where score>=90);

 示例三: 子查询的结果不仅仅能作为条件, 还可以作为一张表来使用, 但是作为一张表来使用必须起别名

 select * from stu where score >=60;
 select name, city, score from stu;
 select name, city, score from stu where score >=60;

 select name, city, score from (select * from stu where score >=60) as t;
上一篇 下一篇

猜你喜欢

热点阅读