Mysql - 3个表中的3个单独的总和 - 工作 - 搜索更好的查询

时间:2014-10-31 13:45:26

标签: mysql sql

故事:我有一个mysql表,我得到3个值(总和)与下面的查询。查询正在运行。但这需要7.624秒,对我来说太长了。只是想找到一个更好的SQL查询。你能救我吗?

SELECT
    DATE(a.tarih),
    (
        SELECT
            SUM(s.stoplam)
        FROM
            siparis s
        WHERE
            s.durum_id IN (4, 26, 27, 28, 29)
        AND DATE(s.tarih) = DATE(a.tarih)
    ) AS iptal,
    (
        SELECT
            SUM(c.stoplam)
        FROM
            siparis c
        WHERE
            c.durum_id NOT IN (4, 26, 27, 28, 29)
        AND DATE(c.tarih) = DATE(a.tarih)
    ) AS Ciro,
    (
        SELECT
            SUM(d.stoplam)
        FROM
            siparis d
        WHERE
            d.durum_id NOT IN (4, 26, 27, 28, 29)

        AND DATE(d.tarih) = DATE_ADD(
            DATE(a.tarih),
            INTERVAL - 30 DAY
        )
    ) AS GCiro
FROM
    siparis a
WHERE
    DATE(a.tarih) > DATE_ADD(CURDATE(), INTERVAL - 30 DAY)
GROUP BY
    DATE(a.tarih)

1 个答案:

答案 0 :(得分:1)

我认为你可以通过条件聚合更容易地做到这一点,除了第三个总和:

SELECT DATE(a.tarih),
       SUM(CASE WHEN s.durum_id IN (4, 26, 27, 28, 29) THEN s.stoplam ELSE 0 END) as iptal,
       SUM(CASE WHEN s.durum_id NOT IN (4, 26, 27, 28, 29) THEN s.stoplam ELSE 0 END) as Ciro,
       (SELECT SUM(d.stoplam)
        FROM siparis d
        WHERE d.durum_id NOT IN (4, 26, 27, 28, 29) AND
              DATE(d.tarih) = DATE_ADD(DATE(a.tarih), INTERVAL - 30 DAY)
       ) AS GCiro
FROM siparis a
WHERE DATE(a.tarih) > DATE_ADD(CURDATE(), INTERVAL - 30 DAY)
GROUP BY DATE(a.tarih);