我想計算總購買次數以及item_id隨時間推移的購買次數。在這個例子中,用戶可以擁有一個物品,這些物品可以由其他用戶購買。業主不能購買他們自己的物品。MYSQL包括具有零項計數的日期的值
我遇到的問題是如何在沒有任何採購與正整數計數一起購買的情況下返回計數爲「0」的結果。
這裏是我的表:
items | items_purchased | numbers | dates
i_id item_id user_id | p_id item_id user_id date | num | datefield
1 1 11 | 1 1 13 2009-01-11 | 1 | 2005-06-07
2 2 12 | 2 1 14 2009-01-11 | 2 | 2005-06-08
3 3 11 | 3 2 15 2009-01-12 | 3 | 2005-06-09
| 4 3 16 2009-01-12 | ... | ...
| 5 1 17 2011-12-12 | 1000 | 2015-06-07
這裏是我的MySQL查詢的user_id=11
的項目採購的總數:
SELECT COUNT(*) as counts, DATE(purchase_date) as DATE
FROM items_purchased
JOIN items on items_purchased.item_id=items.item_id
WHERE items.user_id=11
GROUP BY DATE(purchase_date)
//note this query **doesn't** make use of the numbers and dates tables b/c I don't know how to use them
這裏的結果:
counts date
2 2009-01-11
1 2009-01-12
1 2011-12-12
這裏的我想看看:
counts date
2 2009-01-11
1 2009-01-12
0 2009-01-13
0 ... // should be a row here for each day between 2009-01-13 and 2011-12-12
1 2011-12-12
0 ... // should be a row here for each day between 2011-12-12 and current date
0 current date (2012-6-27)
這是我對商品的總數量限制爲item_id=1
這是由user_id=11
擁有MySQL查詢:
SELECT COUNT(*) as counts, DATE(purchase_date) as DATE
FROM items_purchased
JOIN items on items_purchased.item_id=items.item_id
WHERE items.user_id=11 and items.item_id=1
GROUP BY DATE(purchase_date)
這裏的結果:
counts date
2 2009-01-11
1 2011-12-12
上述類似,這裏就是我想看看:
counts date
2 2009-01-11
0 2009-01-12
0 ... // should be a row here for each day between 2009-01-12 and 2011-12-12
1 2011-12-12
0 ... // should be a row here for each day between 2011-12-12 and current date
0 current date (2012-6-27)
不知怎的,我想我需要納入numbers
和dates
表,但我不知道如何做到這一點。任何想法,將不勝感激,
感謝, 添
可能重複的[從數據庫通過MySQL檢索缺失的日期](http://stackoverflow.com/questions/2978129/retrieve-missing-dates-from-database-via-mysql) – Bohemian
@Bohemian謝謝我見過很多這些示例在SO上,我是絕對的無法理解如何將它們應用於我的查詢。我還在學習MySQL,因此我很難推斷... –