【问题标题】:SELECT statement using WHERE IN and HAVING COUNT fails使用 WHERE IN 和 HAVING COUNT 的 SELECT 语句失败
【发布时间】:2013-10-03 19:58:35
【问题描述】:

我有以下查询来返回所有具有指定标签的 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 的数据库,就像 WHERE 一样
  • 谢谢,如果您将此添加为答案,我会接受。我一直将 GROUP BY 放在错误的位置并出现语法错误。需要在 HAVING 之前和 WHERE AND 之后。
  • 您可能需要在此特定查询中使用 GROUP BY user_attributes.attribute_id(因为您说要返回所有 user_attributes ...)但没有 GROUP BYHAVING 在其他情况下有效且有用。

标签: mysql where having where-in


【解决方案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

【讨论】:

    猜你喜欢
    • 2012-08-12
    • 2016-02-06
    • 1970-01-01
    • 2010-12-07
    • 2016-12-29
    • 2010-12-23
    • 2021-12-23
    • 2011-01-12
    • 1970-01-01
    相关资源
    最近更新 更多