6.4高级查询:分组查询 链接查询 子查询 联合查询
—:分組查詢
?? 1 group by
????????? select *from car group by powers;
???????? 按powers字段分組顯示,去除重復(fù)項。
????????? select *from car group by powers,oil;
??????? 先按第1個字段分組,然后在第1個字段值相同的記錄中,
??????? 再根據(jù)第2個字段的值進行分組.
??? 2 group by group_concat(字段名)
????? select powers,group_concat(oil) from car group by powers;
????? 按powers字段分組后,顯現(xiàn)每個powers字段里oil的數(shù)值。
????? select oil,group_concat(powers) from car group by oil;
??? 3 group by +函數(shù)
??? 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的個數(shù),后面一列會再最下方顯示上面所有項的和
???? 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字段分組,數(shù)出每個項不同值的個數(shù)再挑出個數(shù)大于1的。
??? select powers,avg(price) from car group by powers having avg(price)>50;
二 鏈接查詢
??? 1 內(nèi)鏈接
???? 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;
???? 自動清除笛卡爾積,把重復(fù)的列合并
???? 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的 所以導(dǎo)致外層查詢不執(zhí)行
?select * from student where sid = 1 and exists (select sid from score where sid = 1)
select * from student where exists(子查詢是否返回有結(jié)果集,如果有,則執(zhí)行外層查詢,如果沒有,
則不執(zhí)行外層查詢)
四 聯(lián)合查詢:查詢時,查詢的字段個數(shù)要一樣
union all
select * from student
union all
select *from student
把兩張表拼在一起沒有去重效果
union
select * from student
union
select *from score
兩個表聯(lián)合查詢時,如果兩行數(shù)據(jù)每一列都相同(無論時什么類型,只要值一樣)就合并去重
轉(zhuǎn)載于:https://www.cnblogs.com/sunhao1987/p/9135064.html
《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的6.4高级查询:分组查询 链接查询 子查询 联合查询的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 转 linux常用查看硬件设备信息命令
- 下一篇: Spring Cloud (3) 服务消