简体   繁体   English

MySQL查询-获取“大于…”的列值

[英]MySQL query - get column values “greater than…”

I have this query: 我有这个查询:

$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

However I want to change the 6 line to: 但是我想将6行更改为:

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

but it doesn't seems the correct way to do, it doesn't work. 但这似乎不是正确的方法,它不起作用。

Any ideas ? 有任何想法吗 ?

Remove that line from your WHERE clause and put in a HAVING clause. 从WHERE子句中删除该行,然后放入HAVING子句。 A HAVING clause will look at aggregate results. HAVING子句将查看汇总结果。 WHERE does not. 在哪里没有。

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

This line is redundant and could be dropped: AND (timecode >= '-5' AND timecode <= '15') 该行是多余的,可以删除:AND(时间代码> ='-5'AND时间代码<='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

You can't use aggregated fields in a WHERE clause. 您不能在WHERE子句中使用聚合字段。 count() results are only available after ALL applicable rows have been considered. 仅在考虑了所有适用的行之后, count()结果才可用。 But the where filtering is done as each individual row is parsed. 但是在解析每个单独的行时将where过滤。 Cliche statement, but you're trying to count your chickens before they've hatched. 陈词滥调,但您要在孵出鸡之前先数数鸡。

Such things have to be done with a HAVING clause, which is basically exactly the same as a where , but is applied just before the final results are sent back to the client. 此类操作必须使用HAVING子句完成,该子句与where完全相同,但仅在将最终结果发送回客户端之前应用。 So... 所以...

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

HAVING (n_tags > 3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM