[英]SELECT not working when using != in WHERE clause (using GROUP BY and HAVING COUNT)
[英]SELECT statement using WHERE IN and HAVING COUNT fails
我有以下查询可返回所有具有指定标签的user_attributes和属性:
SELECT `user_attributes`.*, `attributes`.*
FROM `user_attributes`
INNER JOIN `attributes` ON (`attributes`.`id` = `user_attributes`.`attribute_id`)
INNER JOIN `user_tags` ON (`attributes`.`id` = `user_tags`.`attribute_id`)
INNER JOIN `tags` ON (`user_tags`.`tag_id` = `tags`.`id`)
WHERE `user_attributes`.`user_id` = '1'
AND `tags`.`title` IN ('tag1')
我想调整查询,以便找到具有2个标记的所有值。 目前,我有:
SELECT `user_attributes`.*
FROM `user_attributes`
INNER JOIN `attributes` ON (`attributes`.`id` = `user_attributes`.`attribute_id`)
INNER JOIN `user_tags` ON (`attributes`.`id` = `user_tags`.`attribute_id`)
INNER JOIN `tags` ON (`user_tags`.`tag_id` = `tags`.`id`)
WHERE `user_attributes`.`user_id` = '1'
AND `tags`.`title` IN ('tag1', 'tag2')
HAVING (COUNT(DISTINCT `tags`.`title`) = 2)
是否因为我使用没有GROUP BY的HAVING而中断?
确实应将HAVING与GROUP BY结合使用。 MySQL是唯一可以在没有GROUP BY的情况下处理HAVING的数据库
还有更多的证据可以证明这个低俗的人..
MySQL http://www.sqlfiddle.com/#!2/ba8d6/3 (this is WRONG and looks like HAVING IS USED AS WHERE)
Oracle http://www.sqlfiddle.com/#!4/ba8d6/1 (this is correct ORA-00979: not a GROUP BY expression Oracle is missing the GROUP BY)
Postgresql http://www.sqlfiddle.com/#!1/ba8d6/2 (this is correct ERROR: column "data.username" must appear in the GROUP BY clause or be used in an aggregate function Postgresql wants to have an GROUP BY
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.