高级查询
Posted 所爱隔山隔海
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了高级查询相关的知识,希望对你有一定的参考价值。
一、分组查询
1、group by:
select * from car group by powers;
2、group by group_concat(字段名) :
select powers,group_concat(name) from car group by powers;
3、group by +函数;
4、group by = with rollup;
select oil,powers from car group by powers with rollup;
5、group by + having + 条件:
select powers,count(*) from car group by powers having count(*)>1;
select powers,avg(price) from car group by powers having avg(price)>50;
二、链接查询
1、内连接:
select a.sid,sname,gcourse,gscore from student as a,score as b
where a.sid = b sid and a.sid = 3 and b.gcourse = "chinese";
select a.sid,sname,gcourse,gscore from student as a,inner join score
as b where/on a.sid = b.sid and a.sid = 3 and b.sid = "chinese";
2、左链接:
select a.sid,sname,gcourse,gscore from student as a left join score as b on a.sid = b.sid
and a.sid = 3 and b.gcourse = "chinese";
3、右链接:
select a.sid,sname,gcourse,gscore from student as a right join score as b on a.sid = b.sid
and a.sid = 3 and b.gcourse = "chinese";
4、自然链接:
select * from student as a natural join score as b
自动清除笛卡尔积,把重复的列合并
5、交叉链接:
select * from student as a corss join score as b;
会形成笛卡尔积
三、子查询:
select name price from (select * from car where powers =130) as aa;
[必须起别的名字]
any/more:
select * from student where sid > any/more(select gid from score)
all:
select * from student where sid > all (select gid from score)
exists:
select * from student where exists (select sid from score where sid = 88)
【因为score表中sid没有等于88的 所以 导致外层查询不执行】
select * from student where sid = 1 and exists (select sid from score where sid = 1)
select * from student where exists (子查询是否返回有结果集,如果有,则执行外层查询,
如果没有,则不执行外层查询)
四、联合查询:查询时,查询的字段个数要一样
union all
例如 select *from student union all select * from score
【把两个表拼接在一起,没有去重效果】
uniom
例如 select *from student union select *from socer
【两个表联合在一起查询时,如果两行数据每一列相同(无论是什么类型只要值一样,就会合并去重)】
]
以上是关于高级查询的主要内容,如果未能解决你的问题,请参考以下文章