【问题标题】:optimize my log report query优化我的日志报告查询
【发布时间】: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


【解决方案1】:

你想做条件聚合:

select '$variable' as cell,
        count(distinct case when fmonth = '2015-01' then cellno end) as jan,
        count(distinct case when fmonth = '2015-02' then cellno end) as feb,
        . . . 
        count(distinct case when fmonth = '2015-12' then cellno end) as dec
FROM smsreports s
WHERE s.cellno = '$variable';

【讨论】:

  • 感谢@gordon,这很有帮助......你能再帮忙做一件事吗,我试图研究查询优化,你能给我发送任何全面的链接,我可以在其中获得有关优化的所有信息