sql语句如下,前面是执行时间,求教怎么把查询速度优化至最大。
array(2) {
[0] => string(6) "4.1184"
[1] => string(316) "select a.custid from g_customer_tb a join g_customer_tbdata b on a.custid = b.custid where (b.rq > '2016-01-29 00:00:00 ' and b.rq < '2018-01-27 23:59:59') and a.shopid in (5,7,18,29,47,77,78,86,87,88,196,197,198,199) and( a.size1 = 1 or a.size2 = 1 or a.size3 = 1 ) group by b.custid having count(b.id) = 1"
}
sql语句如下,前面是执行时间,求教怎么把查询速度优化至最大。
array(2) {
[0] => string(6) "4.1184"
[1] => string(316) "select a.custid from g_customer_tb a join g_customer_tbdata b on a.custid = b.custid where (b.rq > '2016-01-29 00:00:00 ' and b.rq < '2018-01-27 23:59:59') and a.shopid in (5,7,18,29,47,77,78,86,87,88,196,197,198,199) and( a.size1 = 1 or a.size2 = 1 or a.size3 = 1 ) group by b.custid having count(b.id) = 1"
}
看起来也没啥问题,就是给你加了个日期用between and 来查,
要确定rq是字符串类型的 (如果是mssql的字符串也行) 并且有索引,其他查询条件也没啥加索引的意义
或者如果想飞速,给常用的查询做个统计专用的表,定期整理这个表,统计从这个新表里查就快多了
第一个日期里后面多个空格 不知道有影响没
SELECT a.custid
FROM g_customer_tb a
JOIN g_customer_tbdata b ON a.custid = b.custid
WHERE b.rq between '2016-01-29 00:00:00' AND '2018-01-27 23:59:59'
AND a.shopid IN (5,
7,
18,
29,
47,
77,
78,
86,
87,
88,
196,
197,
198,
199)
AND (a.size1 = 1 OR a.size2 = 1 OR a.size3 = 1)
GROUP BY b.custid
HAVING COUNT (b.id) = 1
去问一下bing吧,哪儿应该有
两个时间条件没必要用括号吧,虽然没什么影响。
用or会影响后面的查询条件,会大大的降低效率,看看能不能根据业务需求改成其他的写法。
如果shopid in 的条件是个子查询的话,改成exists 应该好一点,其他的真没看出来。
其他的就是加索引吧
你这个语句问题不大,关键是字段索引没有建的话,效率不会太高,用in or group 这种都是影响效率的
1、加了索引没用的,不会走建立的索引,基本都是走聚集,
2、建议是拆分语句,将各字段的条件拆开来,如,先按照rq,将结果查询出来,再按照shopid in(...)来查询
3、在拆开的字段上建立索引,但是也要注意是否合适,如在rq上建立索引