Question

I have the following query to return all user_attributes and attributes which have a specified tag:

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. 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?

Was it helpful?

Solution

HAVING should be used in combination with GROUP BY indeed. MySQL is the only database what will handle HAVING without GROUP BY as some kind off WHERE

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top