优化工会和常见条件的查询

时间:2012-12-10 20:28:32

标签: mysql sql database

我有大约18个选择的联合,每个选择包含几乎10个条件,只有一个条件不同。请查看下面的sql结构。

SELECT count(*) AS count, 'blue' as title 
FROM Users
WHERE [a long list of conditions,which are identical] AND eyes='blue'

UNION

SELECT count(*) AS count, 'hazel' as title 
FROM Users
WHERE [a long list of conditions,which are identical] AND eyes='hazel'

UNION

SELECT count(*) AS count, 'Black' as title 
FROM Users
WHERE [a long list of conditions,which are identical] AND eyes='black'

等等。

检索此类数据的更好方法是什么。有更好的想法吗?

编辑:

很抱歉没有提到这个,这些条件不是基于单个字段“眼睛”,它可以是不同的例如毛发,高度等。所以group by不能按建议使用。

3 个答案:

答案 0 :(得分:4)

你想要条件总和:

select count(*),
       sum(case when eyes = 'blue' then 1 else 0 end) as blue,
       sum(case when eyes = 'hazel' then 1 else - end) as hazel,
       . . . 
from users
where <long list of conditions>

这会将所有内容放在一行上。要将所有内容放在不同的行上,您可能需要:

select eyes, count(*)
from users
where <long list of conditions>
group by eyes

这将为每种眼睛颜色提供单独的行。

根据您的评论,最好的方法可能是在一行上进行汇总,然后取消值。不幸的是,MySQL没有一个univot,所以以下,虽然丑陋应该是有效的:

select titles.title,
       max(case when titles.title= 'blue' then blue
                when titles.title = 'hazel' then hazel
                . . .
           end) as cnt
from (select count(*) as cnt,
             sum(case when eyes = 'blue' then 1 else 0 end) as blue,
             sum(case when eyes = 'hazel' then 1 else - end) as hazel,
             . . . 
      from users
      where <long list of conditionss
     ) cross join
     (select 'blue' as title union all
      select 'hazel' union all
      . . .
     ) titles
group by titles.title

答案 1 :(得分:2)

虽然这不是与上面完全相同的输出,但是

select eyes, count(*)
from Users
where [a long list of conditions,which are identical]
group by eyes

应该为您提供所需的信息。

答案 2 :(得分:0)

如果您尝试获取每种眼睛颜色的用户数量,您应该尝试:

SELECT count( * ) AS c, 'eye'
FROM Users
WHERE .... all your conditions here ...
GROUP BY 'eye'