WHERE跨越多个UNION ALL语句

时间:2015-07-28 11:16:54

标签: mysql

我有一个SQL select语句,其中包含多个UNION ALL个关键字,用于连接其他独立的SQL语句。如果没有UNION ALL关键字,我的查询就太复杂了。

但是,我想将所有子查询限制到特定的日期范围,我不想在每个子查询的末尾写出完全相同的where子句。有没有办法可以为所有人写一个WHERE条款?

我尝试了以下代码,但它不起作用,因为COUNT(*)短语阻止了对每条记录过滤inputDate列。此外,从性能角度来看,如果有办法,最好先按日期栏进行过滤。

SELECT * FROM (
    SELECT count(*), inputDate 'sel1' as name FROM tblName WHERE name IN ('n1','n2')
    UNION ALL
    SELECT count(*), inputDate, 'sel2' as name FROM tblName WHERE name IN ('n3','n4')
    UNION ALL
    SELECT count(*), inputDate, 'sel3' as name FROM tblName WHERE name IN ('n5','n6')
) names WHERE inputDate >= DATE_SUB(NOW(), INTERVAL 1 MONTH)

1 个答案:

答案 0 :(得分:2)

您需要在外部查询中执行count(*)

SELECT name, count(*), inputdate
FROM (SELECT inputDate, 'sel1' as name FROM tblName WHERE name IN ('n1','n2')
      UNION ALL
      SELECT inputDate, 'sel2' as name FROM tblName WHERE name IN ('n3','n4')
      UNION ALL
      SELECT inputDate, 'sel3' as name FROM tblName WHERE name IN ('n5','n6')
     ) names
WHERE inputDate >= DATE_SUB(NOW(), INTERVAL 1 MONTH)
GROUP BY name;

编辑:

实际上,如果这些都来自同一张桌子,则不需要union all

select (case when name in ('n1', 'n2') then 'sel1'
             when name in ('n3', 'n4') then 'sel2'
             when name in ('n5', 'n6') then 'sel3'
        end) as grp, count(*)
from tblName
where inputDate >= DATE_SUB(NOW(), INTERVAL 1 MONTH) and
      name in ('n1', 'n2', 'n3', 'n4',' n5', 'n6')
group by grp;