0

我有这个查询:

$score = 10;
SELECT timecode, count(tag) as n_tags, tag
FROM dados
WHERE dados.tag = 'tag1' 
AND dados.filename = 'file.mp4'
AND (timecode >= '-5' AND timecode <= '15')
AND (timecode = '$score')
GROUP BY timecode
ORDER BY count(tag) DESC

但是我想将第 6 行更改为:

AND (timecode = '$score' AND n_tags > 3)

但这似乎不是正确的方法,它不起作用。

有任何想法吗 ?

4

2 回答 2

2

从 WHERE 子句中删除该行并放入 HAVING 子句。HAVING 子句将查看汇总结果。WHERE 没有。

SELECT timecode, count(tag) as n_tags, tag
FROM dados
WHERE dados.tag = 'tag1' 
AND dados.filename = 'file.mp4'
AND (timecode >= '-5' AND timecode <= '15')
AND (timecode = '$score')
GROUP BY timecode
HAVING count(tag) > 3
ORDER BY count(tag) DESC

此行是多余的,可以删除:AND (timecode >= '-5' AND timecode <= '15')

SELECT timecode, count(tag) as n_tags, tag
FROM dados
WHERE dados.tag = 'tag1' 
AND dados.filename = 'file.mp4'
AND (timecode = '$score')
GROUP BY timecode
HAVING count(tag) > 3
ORDER BY count(tag) DESC
于 2013-02-20T14:32:23.600 回答
2

您不能在 WHERE 子句中使用聚合字段。count()只有在考虑了所有适用的行后,结果才可用。但是where过滤是在解析每一行时完成的。陈词滥调,但你试图在孵化之前数数你的鸡。

此类事情必须使用子句来完成,该HAVING子句与 a 基本完全相同where,但在最终结果发送回客户端之前应用。所以...

SELECT ..., count(tag) as n_tags
...
WHERE (timecode = '$score')

HAVING (n_tags > 3)
于 2013-02-20T14:33:26.953 回答