6.4高级查询:分组查询 链接查询 子查询 联合查询

—:分组查询
   1 group by
          select *from car group by powers;
         按powers字段分组显示,去除重复项。
          select *from car group by powers,oil;
        先按第1个字段分组,然后在第1个字段值相同的记录中,
        再根据第2个字段的值进行分组.
    2 group by group_concat(字段名)
      select powers,group_concat(oil) from car group by powers;
      按powers字段分组后,显现每个powers字段里oil的数值。
      select oil,group_concat(powers) from car group by oil;
    3 group by +函数
    select powers, sum(oil) from car group by powers;
    按powers 字段分组,再把分组后的powers每一项的oil相加。
    4 group by + with rollup
     select oil,count(powers) from car group by oil with rollup;
     按oil字段进行分组,再算出分组后每个oil值中powers的个数,后面一列会再最下方显示上面所有项的和
     select oil, group_concat(powers) from car group by oil with rollup;
     select powers,avg(price) from car group by powers with rollup;
    5 group by + having + 条件
    select powers,count(*) from car group by powers having count(*)>1;
    按powers字段分组,数出每个项不同值的个数再挑出个数大于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, a.sname, b.gcourse, b.gscore from student as a inner join score as b
     on a.sid = b.sid and a.sid = 3 and b.gcourse ='English';
    2 左链接
     select a.sid,a.sname,b.gcourse,b.gscore from student as a left join
     score as b on a.sid = b.sid and a.sid = 3 and b.gcourse = 'English';
     3 右链接
     select a.sid,a.sname,b.gcourse,b.gscore from student as a right join
     score as b on a.sid = b.sid and a.sid = 3 and b.gcourse = 'English';
     4 自然链接
     select * from student as a natural join score as b;
     自动清除笛卡尔积,把重复的列合并
     5 交叉链接
     select * from student as a cross join score as b;
     会行程笛卡尔积
     将A表的所有行分别与B表的所有行进行连接。
三 子查询
 select name,price from(select *from car where powers = 130) as aa;(必须起名)
 any/some
 
 select *from student where sid > any/some(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 student
把两张表拼在一起没有去重效果

union

select * from student
union
select *from score
两个表联合查询时,如果两行数据每一列都相同(无论时什么类型,只要值一样)就合并去重

猜你喜欢

转载自www.cnblogs.com/sunhao1987/p/9135064.html
今日推荐