日期:2014-05-16  浏览次数:20538 次

一个sql查询相关的问题
有一个表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 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

------解决方案--------------------
用group by+1
自己研究一下怎么写
实在不行用缓存减少查询...