无论如何要使联盟声明更小?

时间:2012-01-06 11:37:19

标签: mysql

无论如何,我可以将这句话缩小吗?为了提高效率,整个想法就是得到 今天,本月和最后几个月的“报价”数量。

    SELECT COUNT(QuoteDate) AS today
    FROM database
    WHERE QuoteDate >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)

    UNION

    SELECT COUNT(QuoteDate) AS this_month
    FROM database
    WHERE QuoteDate >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH)

    UNION

    SELECT COUNT(QuoteDate) AS last_month
    FROM database 
    WHERE QuoteDate >= DATE_SUB(CURRENT_DATE(), INTERVAL 2 MONTH)

由于

2 个答案:

答案 0 :(得分:3)

难道你不能只使用OR语句吗?

 SELECT COUNT(QuoteDate) AS today FROM database
    WHERE 
     QuoteDate >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)
     OR 
     QuoteDate >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH)
     OR
     QuoteDate >= DATE_SUB(CURRENT_DATE(), INTERVAL 2 MONTH)

答案 1 :(得分:1)

未测试:

SELECT
    sum(if(quotedate >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY), 1, 0)) AS today,
    sum(if(quotedate >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), 1, 0)) AS this_month,
    sum(if(quotedate <= DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), 1, 0)) AS last_month
FROM database
WHERE QuoteDate >= DATE_SUB(CURRENT_DATE(), INTERVAL 2 MONTH)

我们的想法是将where子句中的选择移动到field子句并在那里进行计算。

请注意,第三个条款是相反的,因为您可能只需要那些超过1个月的条目。