【发布时间】:2015-05-01 03:36:03
【问题描述】:
我正在制作一个日志报告,其中我编写了一个查询以从数据库中获取结果,但是它太慢了,结果非常慢。有人为我优化它,并告诉我一些学习优化的链接。查询在这里:
select '$variable' as cell,
COALESCE(( SELECT count(distinct cellno) FROM smsreports s WHERE s.cellno = '$variable' AND fmonth = '2015-01')) as jan,
COALESCE(( SELECT count(distinct cellno) FROM smsreports s WHERE s.cellno = '$variable' AND fmonth = '2015-02')) as feb,
COALESCE(( SELECT count(distinct cellno) FROM smsreports s WHERE s.cellno = '$variable' AND fmonth = '2015-03')) as mar,
COALESCE(( SELECT count(distinct cellno) FROM smsreports s WHERE s.cellno = '$variable' AND fmonth = '2015-04')) as apr,
COALESCE(( SELECT count(distinct cellno) FROM smsreports s WHERE s.cellno = '$variable' AND fmonth = '2015-05')) as may,
COALESCE(( SELECT count(distinct cellno) FROM smsreports s WHERE s.cellno = '$variable' AND fmonth = '2015-06')) as jun,
COALESCE(( SELECT count(distinct cellno) FROM smsreports s WHERE s.cellno = '$variable' AND fmonth = '2015-07')) as jul,
COALESCE(( SELECT count(distinct cellno) FROM smsreports s WHERE s.cellno = '$variable' AND fmonth = '2015-08')) as aug,
COALESCE(( SELECT count(distinct cellno) FROM smsreports s WHERE s.cellno = '$variable' AND fmonth = '2015-09')) as sep,
COALESCE(( SELECT count(distinct cellno) FROM smsreports s WHERE s.cellno = '$variable' AND fmonth = '2015-10')) as oct,
COALESCE(( SELECT count(distinct cellno) FROM smsreports s WHERE s.cellno = '$variable' AND fmonth = '2015-11')) as nov,
COALESCE(( SELECT count(distinct cellno) FROM smsreports s WHERE s.cellno = '$variable' AND fmonth = '2015-12')) as dec
优化此查询以获得结果,请记住我想要每月的结果。
【问题讨论】:
-
你为什么要过滤
cellno
,然后再做count(distinct cellno)
。该值只能是 0 或 1。
标签: php mysql sql database optimization