MySQL 4.1.1 與後續的版本支持WITH ROLLUP修飾符(modifier),可以統計輸出的集合字段。
查找每年的葡萄酒銷售總額:
SELECT year,sum(price) FROM wine
INNER JOIN items ON wine.id = items.wine_id
GROUP BY year;
部分查詢結果:
year sum(price)
1980 2056.12
1981 16234.78
...
2007 18000.12
2008 20183.34
若在查詢中加上WITH ROLLUP
SELECT year,sum(price) FROM wine
INNER JOIN items ON wine.id = items.wine_id
GROUP BY year
WITH ROLLUP;
查詢結果會多一行記錄:
year sum(price)
1980 2056.12
1981 16234.78
...
2007 18000.12
2008 20183.34
NULL 5893233.21
多出的這一行,年份顯示null,sum(price)是銷售額的總計,如此處理便可省去如下代碼的運行:
SELECT sum(price) FROM wine
INNER JOIN items ON wine.id = items.wine_id;
找出每種葡萄酒的銷售總額:
在查找過程中,加入了產酒區(region)、酒廠表(winery),便可使用WITH ROLLUP 取得各個酒廠與產酒區的銷售金額
關鍵:在GROUP BY子句中使用region與winery表的唯一值。
SELECT region_name,winery_name,wine_id,sum(price) FROM region
INNER JOIN winey ON region.id = winery.region_id
INNER JOIN wine ON wine.winery_id = winery.id
INNER JOIN items ON wine.id = items.wine_id
GROUP BY region_name,winery_name,wine.id
WITH ROLLUP;
部分查詢結果:
region_name winery_name wine_id sum(price)
barissa anderson wines 112 682.3
barissa anderson wines 113 732.4
barissa anderson wines 114 1123.3
barissa anderson wines 115 68.1
barissa anderson wines NULL 2001.8
...
barissa NULL NULL 698403.5
...
NULL NULL NULL 4287403.6
第六行顯示anderson wines酒廠的總銷售額(前五行的和),同樣其他酒廠的總銷售額都會列在該酒廠數據的後面,barissa地區的所有酒廠查詢完畢後,barissa地區的總金額會出現在winery_name 和wine_id均爲null的那一行,最後一行,是所有的地區、酒廠、酒品種銷售額的總和。
WITH ROLLUP特點:
- ORDER BY 子句不能和WITH ROLLUP 同時使用;
- 輸出產生後纔會運用LIMIT子句,所以總會包含總計是NULL的數據行。