有一個表groups,下面有很多個欄位
id
user
cost
type
addtime
uptime
note
.....
type裡面有5個類型,分別是001-005,
現在要的結果就是查詢最近6個月,001-005的總數,
比如查詢一月份,1號到31號,TYPE為001-005的資料
select count(*) from groups where type='001' and addtime<='20130101' and addtime >= '20130130'
select count(*) from groups where type='002' and addtime<='20130201' and addtime >= '20130230'
select count(*) from groups where type='003' and addtime<='20130301' and addtime >= '20130330'
select count(*) from groups where type='004' and addtime<='20130401' and addtime >= '20130430'
select count(*) from groups where type='005' and addtime<='20130501' and addtime >= '20130530'
查詢6個月的話就需要查詢30次。
如果有很多人登入這個系統,查詢這樣的SQL很耗費時間,我試過如果同時三個人都開啟這個頁面,大概反應時間要3秒以上
我的思路就是有沒有辦法把這些查詢結果寫到一個表裡面,這樣查詢的時候我直接查詢的表的資料 ,然後這些SQL的資料我可以設定一個時間
自動查詢結果然後更新到一個表裡面。這樣我直接從表裡面查詢資料比用 count查詢來得快,但是這個應該怎麼實現呢,我現在用的就是最笨的
辦法,一個一個來查詢,好卡啊。
回複討論(解決方案)
select count(*) from groups where type in('001','002','003','004','005') and addtime>='20130101' and addtime <= '20130630'
select count(*) from groups where type in('001','002','003','004','005') and addtime>='20130101' and addtime <= '20130630'
你好,謝謝回複,這樣查詢出來就是一個總和,我想要單獨的一個值
比如TYPE =001 一月份 總數是 20
TYPE=002 1月份 總數是500
TYPE=003 1月份 總數是3987
TYPE=004 1月份 總數是9898
TYPE=005 1月份 總數是123
select count(*) from groups where addtime>='20130101' and addtime <= '20130630' group by addtime,type
select type, left(addtime,6) as addtime, count(*) as cnt from groups group by 1, 2
那連in都不用了 group by type, DATE_FORMAT(addtime,‘m%’) 這樣試一下
select count(*) from groups where addtime>='20130101' and addtime <= '20130630' group by MONTH(addtime),type
select count(*) from groups where addtime>='20130101' and addtime <= '20130630' group by substring(addtime,4,2),type
2中方式:
1、使用SQL寫暫存資料表
2、建立where條件相關的索引;
暫存資料表是個不錯的選擇,資料處理完就自動釋放了!
用group by+1
自己研究一下怎麼寫
實在不行用緩衝減少查詢...