1. 程式人生 > >SQL 筆記1,left join,group by,having

SQL 筆記1,left join,group by,having

rom from 報錯 order by use join unknown and select

表:XS,XK,CJ

left join 表1 on 表1.字段=表2.字段

group by 分組條件

order by 排序條件 asc正序(小到大),desc倒序

having 跟條件類似where,不過需要在返回集字段中包含該字段

否則會報錯:Unknown column ‘c.CJ‘ in ‘having clause‘,未知的列,在having

例:

#查詢有不及格的成績的學生姓名
SELECT
s.XSMC, c.CJ
FROM cj c
LEFT JOIN xs s ON s.XSDM=c.XSDM
LEFT JOIN xk k ON k.XKDM=c.XKDM
GROUP BY c.XSDM
HAVING c.CJ <60

#查詢所有學生所有學科的成績<=60
SELECT
s.XSMC,k.XKMC,c.CJ
FROM xs s,xk k,cj c
WHERE s.XSDM = c.XSDM
AND k.XKDM = c.XKDM
AND c.CJ <= 60


#查詢學生總成績
#ASC正序小到大,DESC倒序大到小
SELECT s.XSMC, SUM(c.CJ)
FROM xs s,xk k,cj c

WHERE s.XSDM = c.XSDM
AND k.XKDM = c.XKDM
GROUP BY c.XSDM
ORDER BY
SUM(c.CJ) ASC

SQL 筆記1,left join,group by,having