用于在子查询中求和的备用mysql查询

时间:2014-01-13 13:21:51

标签: mysql sql performance

我有一个包含以下字段的表:

date,amount,status

我有一个查询,它返回每天的总金额(引用),以及只返回给定状态的总和(已售出)。

这很慢,我试图重写查询但没有成功。

原始查询是:

SELECT 
    YEAR(FROM_UNIXTIME(date)) as Year,
    lpad(MONTH(FROM_UNIXTIME(date)), 2, 0) as Month,
    lpad(DAY(FROM_UNIXTIME(date)), 2, 0) as Day,
    (SELECT 
            sum(amount)
        FROM
            mytable
        where
            status = 'SOLD'
                and YEAR(FROM_UNIXTIME(date)) = Year
                and lpad(MONTH(FROM_UNIXTIME(date)), 2, 0) = Month
                and lpad(DAY(FROM_UNIXTIME(date)), 2, 0) = Day) as Sold,
    (SELECT 
            sum(amount)
        FROM
            mytable
        WHERE
            YEAR(FROM_UNIXTIME(date)) = Year
                and lpad(MONTH(FROM_UNIXTIME(date)), 2, 0) = Month
                and lpad(DAY(FROM_UNIXTIME(date)), 2, 0) = Day) as Quoted
FROM
    mytable
group by Year , Month , Day

输出如下(YYYY MM DD SUM):

2013      12         01           3442.00

有没有更好的方法来写这个,所以它立即执行?表中记录的记录少于10,000条。

1 个答案:

答案 0 :(得分:0)

您至少可以避免使用子查询

SELECT 
    YEAR(FROM_UNIXTIME(date)) as Year,
    lpad(MONTH(FROM_UNIXTIME(date)), 2, 0) as Month,
    lpad(DAY(FROM_UNIXTIME(date)), 2, 0) as Day,
    SUM(case
        when status = 'SOLD' then amount
        else 0 end) Sold,
    sum(amount) as Quoted
from
    mytable
GROUP BY Year , Month , Day