【数据库】数据库查询之关键字except,having
數據庫系列主要介紹工作和學習中遇到的一些問題,以下舉例介紹:
假設有個學生成績表 grade, 有4列:id 主鍵標識列,學生姓名 student, 課程course, 考試成績 score, 表數據如下:
?
?
| id | student | course | score |
| 1 | 張三 | 英語 | 70 |
| 2 | 李四 | 英語 | 81 |
| 3 | 王五 | 英語 | 60 |
| 4 | 趙六 | 英語 | 90 |
| 5 | 張三 | 測試 | 50 |
| 6 | 王五 | 測試 | 75 |
| 7 | 張三 | 開發 | 80 |
| 8 | 王五 | 開發 | 90 |
| 9 | 趙六 | 開發 | 85 |
| 10 | 張三 | 數學 | 85 |
| 11 | 王五 | 數學 | 70 |
?
?
1.如果我們想要查詢所有課程成績都大于80分的學生姓名,應該怎么查詢?
?
2.如果我們想要查詢選擇課程數量大于或等于2的學生姓名,應該怎么查詢?
?
解決思路:
一、創建表格
?
create table grade ( id int identity(1,1), student varchar(20), course varchar(20), score int );二、插入數據
?
?
insert into grade values('張三','英語',70); insert into grade values('李四','英語',81); insert into grade values('王五','英語',60); insert into grade values('趙六','英語',90); insert into grade values('張三','測試',50); insert into grade values('王五','測試',75); insert into grade values('張三','開發',80); insert into grade values('王五','開發',90); insert into grade values('趙六','開發',85); insert into grade values('張三','數學',85); insert into grade values('王五','數學',70);?
三、查詢數據
問題1.分析:查詢的是學生姓名student,條件是每科的考試分數都大于80分。
我們可以逆向考慮,查詢分數小于等于80分的學生姓名
?
select distinct student from grade where score<=80因為學生有多門課程,當學生多門課程的分數滿足條件時,會出現重復數據,通過distinct關鍵詞過濾重復數據
?
只要有一門課程的分數小于等于80,就是我們要排除的數據,所以我們可以通過聯合查詢方式差集except進行排除。
查詢所有不重復學生記錄:
select distinct student from grade;差集查詢:
?
?
select distinct student from grade except select distinct student from grade where score<=80;其實except關鍵詞已經有去除重復數據的功能,所以最終可以優化為:
?
?
select student from grade except select student from grade where score<=80;?
如果我不想用差集去查詢,是否還有其他方法呢?其實思路是一樣的,先查詢出分數小于等于80分的學生姓名,然后再排除:
?
select distinct student from grade where student not in (select student from grade where score<=80); select student from grade group by student having student not in (select student from grade where score<=80); select student from grade where student not in (select student from grade where score<=80) group by student;?
第二條和第三條查詢語句結果是一樣的,但是having和where還是有區別,having是分組后篩選,而where是篩選后再分組。
?
問題2.分析:查詢的是學生姓名student,條件是考試的課程大于等于2。
我們知道這里student和course組合是唯一的,所以可以通過對student進行分組,查詢到每個學生的課程數量:
?
select student,COUNT(*) as 課程數量 from grade group by student;然后可以對分組后的數據列表進行篩選,關鍵詞having
?
select student from grade group by student having COUNT(*)>=2;?
這篇文章主要學習了聯合查詢中的差集except(oracle數據庫是minus),not in 排除方法以及分組group by和分組后篩選having.
?
?
?
?
?
?
?
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的【数据库】数据库查询之关键字except,having的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Python】Windows下Pyth
- 下一篇: linux cmake编译源码,linu