一個sql查詢相關的問題

來源:互聯網
上載者:User
有一個表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
自己研究一下怎麼寫
實在不行用緩衝減少查詢...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.