Sql聯合查詢的理解

2021-10-12 07:37:38 字數 1151 閱讀 5398

無意中看到一篇sql聯合查詢的部落格,

[因很久沒有使用複雜的查詢,對於一些sql語句已經很生疏了,花了點時間,自己動手嘗試,終於理解了聯合查詢。資料如下表:

id

type score

'1', '1', '80'

'1', '2', '90'

'1', '3', '99'

'2', '2', '60'

'2', '3', '80'

'3', '1', '80'

'3', '2', '80'

'3', '3', '80'

id可理解為學號,type可理解為課程,score即成績,要求查出每科課程的最高分的學生資訊,

使用分組查詢,select type,max(score) from concurrent_test.new_table group by type;

查詢結果如下:

type score

'1', '80'

'2', '90'

'3', '99'

由此可知type有三種,但是假如我們不知道有哪些具體課程,或者課程是變數,如何優雅的寫sql?

這篇部落格給出的語句是:

select * 

from test as a

where score =

(select min(score)

from score as b

where b.type = a.type)

;

我的理解如下,先查出

select  type,max(score) from concurrent_test.new_table group by type

;

作為一張子表,再依次從全表找出子表的第一行,第二行,第三行…,也即從全表當中查type=1且成績=80的學生資訊,有兩個結果…

最終結果如下:

id

type score

'1', '1', '80'

'1', '2', '90'

'1', '3', '99'

'3', '1', '80'

在這裡記錄下來,以加深理解

SQL 聯合查詢

use xsgl go select from student select from cause select from exam 聯合查詢 join on 預設為inner,如果有right or left 那麼就指的是外聯,outer 可以不寫 1.最長見為內聯 table1 inner jo...

sql聯合查詢

sql查詢 多表聯合查詢 將具有相同的字段的查詢結果合併為乙個表 關鍵字 union 例項 查詢subs表 select subs id,prefix,acc nbr,cust id,user id,acct id,price plan id,area id,update date from sub...

SQL 聯合查詢

a表 aaa bbb ccc 1a 1b 1c 2a 2b 2c 3a 3b 3c b表 aaa bbb ddd 1a 1b 1d 4a 4b 4d 1 union union all all 表示將查詢的所有結果都合併到結果集中,若不加all會將重複的行只保留一行 sql view plain c...