简体   繁体   English

使用WHERE IN和HAVING COUNT的SELECT语句失败

[英]SELECT statement using WHERE IN and HAVING COUNT fails

I have the following query to return all user_attributes and attributes which have a specified tag: 我有以下查询可返回所有具有指定标签的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')

I would like to adjust the query so that it finds all values that have 2 tags. 我想调整查询,以便找到具有2个标记的所有值。 At the moment I have: 目前,我有:

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)

Is it breaking because I'm using HAVING without a GROUP BY? 是否因为我使用没有GROUP BY的HAVING而中断?

HAVING should be used in combination with GROUP BY indeed. 确实应将HAVING与GROUP BY结合使用。 MySQL is the only database what will handle HAVING without GROUP BY as some kind off WHERE MySQL是唯一可以在没有GROUP BY的情况下处理HAVING的数据库

Some more proof for the downvoter.. 还有更多的证据可以证明这个低俗的人..

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.

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