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

时间:2013-10-03 19:58:35

标签: mysql where having where-in

我有以下查询来返回所有具有指定标记的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?

1 个答案:

答案 0 :(得分:-1)

HAVING确实应该与GROUP BY结合使用。 MySQL是唯一一个在没有GROUP BY的情况下处理HAVING的数据库,而不是WHERE

为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