我有这个问题:
$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)
但它似乎不是正确的方法,它不起作用。
有什么想法吗?
答案 0 :(得分:2)
从WHERE子句中删除该行并放入HAVING子句。 HAVING子句将查看聚合结果。没有。
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(时间码&gt; ='-5'和时间码&lt; ='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
答案 1 :(得分:2)
您不能在WHERE子句中使用聚合字段。 count()
结果仅在考虑了所有适用行后才可用。但是where
过滤是在解析每个单独行时完成的。陈词滥调,但是你试图在他们孵化之前计算你的鸡。
这类事情必须使用HAVING
子句完成,该子句与where
基本完全相同,但在最终结果发送回客户端之前应用。所以......
SELECT ..., count(tag) as n_tags
...
WHERE (timecode = '$score')
HAVING (n_tags > 3)