2012-11-26 52 views
0

我有這樣的查詢:MySQL的左連接自或類似

SELECT SUM(spend.price) AS total, WEEKDAY(spend.date) AS weekday 
FROM spend 
WHERE spend.date BETWEEN '2012-11-01' AND '2012-11-07' 
GROUP BY WEEKDAY(spend.date) ; 

眼下查詢給了我只有天中,用戶有一定的款項。

total weekday 
60 2 
10 3 
3  5 
3  6 

但是反而我想每天給我0(零)沒有付款。

total weekday 
0  1 
60 2 
10 3 
0  4 
3  5 
3  6 
0  7 

表格架構here

回答

1

原來這裏是語法:

SELECT SUM(spend.price) AS total, day AS weekday 
FROM (SELECT price, WEEKDAY(date) as day FROM spend WHERE date BETWEEN '2012-11-01' AND '2012-11-07' 
UNION ALL 
SELECT 0,0 
UNION ALL 
SELECT 0,1 
UNION ALL 
SELECT 0,2 
UNION ALL 
SELECT 0,3 
UNION ALL 
SELECT 0,4 
UNION ALL 
SELECT 0,5 
UNION ALL 
SELECT 0,6 
) spend 
GROUP BY day ; 

這裏是一個縮短:

CREATE TEMPORARY TABLE tmp (`price` int, `day` int); 
INSERT INTO tmp VALUES (0,0),(0,1),(0,2),(0,3),(0,4),(0,5),(0,6); 
SELECT SUM(spend.price) AS total, day AS weekday 
FROM (SELECT price, WEEKDAY(date) as day FROM spend WHERE date BETWEEN '2012-11-01' AND '2012-11-07' 
UNION ALL 
SELECT * FROM tmp 
) spend 
GROUP BY day ; 

這裏是一個演示:從你的子查詢http://sqlfiddle.com/#!2/8c323/3/0

+0

刪除日期。否則,這會引發錯誤。 – Tom

+0

@Tom我沒有在我的子查詢中選擇日期,但我必須用它來檢查範圍 –

+0

是的,現在看起來不錯。 – Tom