3

是否有可能count在 select 子句中有一个group by在计数中被抑制的?我需要count忽略该group by子句

我得到了这个查询,它正在计算总条目。该查询是通用生成的,因此我无法进行任何全面的更改,例如子查询等。

在某些特定情况下,需要 group by 来检索正确的行,因此无法删除 group by

SELECT count(dv.id) num
FROM `data_voucher` dv
LEFT JOIN `data_voucher_enclosure` de ON de.data_voucher_id=dv.id
WHERE IF(de.id IS NULL,0,1)=0
GROUP BY dv.id
4

2 回答 2

4

Is it possible to have count in the select clause with a group by which is suppressed in the count? I need the count to ignore the group by clause

well, the answer to your question is simply you can't have an aggregate that works on all the results, while having a group by statement. That's the whole purpose of the group by to create groups that change the behaviour of aggregates:

The GROUP BY clause causes aggregations to occur in groups (naturally) for the columns you name.

cf this blog post which is only the first result I found on google on this topic.

You'd need to redesign your query, the easiest way being to create a subquery, or a hell of a jointure. But without the schema and a little context on what you want this query to do, I can't give you an alternative that works.

I just can tell you that you're trying to use a hammer to tighten a screw...

于 2013-06-09T17:07:27.820 回答
0

找到了使用的替代COUNT DISTINCT方法

SELECT count(distinct dv.id) num
FROM `data_voucher` dv
LEFT JOIN `data_voucher_enclosure` de ON de.data_voucher_id=dv.id
WHERE IF(de.id IS NULL,0,1)=0
于 2013-06-10T06:45:20.983 回答