在查询中使用having子句两次

时间:2014-03-17 19:47:06

标签: mysql sql query-optimization having

我有两个问题

select a,b,c,count(d) as first_count from
test
group by a,b,c
having (count(c)>1)

和第二个

    select a,b,c,count(d) as second_count  from
    test
    group by a,b,c
    having (count(c)>100)

如何在一个查询中执行上述操作,以便在我的结果中我有以下列:a,b,c,count(d) as first_count,count(d) as second_count

3 个答案:

答案 0 :(得分:0)

也许这会对你有所帮助

 select a,b,c,(select count(d)  from test having (count(c)>1) )   as first_count,
              (select count(d)  from test having (count(c)>100) ) as second_count
 FROM test
 group by a,b,c

答案 1 :(得分:0)

如果要合并两个查询结果,可以使用UNION

(select a,b,c,count(d) as first_count ,0 as second_count
from test
group by a,b,c
having first_count>1)
UNION
(select a,b,c,0 as first_count,count(d) as second_count  
from test
group by a,b,c
having second_count>100)

或在单个查询中,您可以使用AND操作或OR操作

根据您的条件使用计数结果进行过滤
select a,b,c,count(d) as first_count from,count(d) as second_count
FROM test
group by a,b,c
having first_count>1 AND second_count >100

答案 2 :(得分:0)

以这种方式试试

SELECT a, b, c, 
       SUM(count >   1) first_count,
       SUM(count > 100) second_count 
  FROM 
(
  SELECT a, b, c, COUNT(*) count
    FROM test
   GROUP BY a, b, c
  HAVING COUNT(*) > 1
) q
 GROUP BY a, b, c