0

指定されたタグを持つすべての 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 を使用しているため、壊れていますか?

4

1 に答える 1

-1

HAVING は、実際には GROUP BY と組み合わせて使用​​する必要があります。MySQL は、GROUP BY なしの HAVING をある種のオフ WHERE として処理する唯一のデータベースです。

反対票を投じた人のためのもう少しの証拠..

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
于 2013-10-03T20:12:08.527 に答える