1.SQL語句匯總 - 聚合函數、分組、子查詢及組合查詢
2.GROUP_CONCAT 筆數串接函數 [MySQL]
簡單的範例
要選擇表單中的村莊名:
SELECT group_concat(village_name separator ',' ) from `village_table`
出來的結果
大都城村,辛北庄村,辛南庄村,辛西庄村
複雜的範例
目的為了呈現多個條件的 SQL 語法。此 SQL 目的是要依供貨商分類取出貨品,並把貨品的流水號產生一個連結的字串 `gdsrec`,並把貨品總價寫成個一值 `sum`
table1: goods 貨品
gsn 流水號
pID 供貨商
price 單價
state 狀態
table2: provider 供貨商
pID 流水號
pname 名稱
關聯 `goods`.`pID` <-> `provider`.`pID`
1
2
3
4
5
6
SELECT
`g`.`pID` , `p`.`pname` ,
group_concat( `g`.`gsn`
order
by
`g`.`gsn` SEPARATOR
','
)
AS
`gdsrec` ,
sum
( `g`.`price` )
AS
`
sum
`
FROM
`goods`
AS
`g`
LEFT
JOIN
`provider`
AS
`p`USING ( `pID` )
WHERE
`g`.`state` =1GROUP
BY
`g`.`pID`
ORDER
BY
`g`.`pID`LIMIT 0 , 30
結果:
table1: goods 貨品
gsn 流水號
pID 供貨商
price 單價
state 狀態
table2: provider 供貨商
pID 流水號
pname 名稱
關聯 `goods`.`pID` <-> `provider`.`pID`
1
2
3
4
5
6
| SELECT `g`.`pID` , `p`.`pname` , group_concat( `g`.`gsn` order by `g`.`gsn` SEPARATOR ',' ) AS `gdsrec` , sum ( `g`.`price` ) AS ` sum ` FROM `goods` AS `g` LEFT JOIN `provider` AS `p`USING ( `pID` ) WHERE `g`.`state` =1GROUP BY `g`.`pID` ORDER BY `g`.`pID`LIMIT 0 , 30 |
pID | pname | gdsrec | sum |
---|---|---|---|
1 | 河馬公司 | 94,94,94,259 | 13947 |
2 | 瘦比八企業社 | 381,381 | 500 |
3 | 張氏企業 | 734,734,734 | 36 |