Strange Having和Group By子句行为生成“'have'子句中的未知列”错误

时间:2016-07-21 13:07:01

标签: mysql sql

我在MySQL数据库中有两个表:

表1

mysql> SELECT ID FROM table1;
+----+
| id |
+----+
|  6 |
+----+
1 row in set (0.00 sec)

表2

mysql> SELECT * FROM table2;
+----+----------+------------------------+----------------------+
| id | placeId  | dictionaryId           | dictionaryCode       |
+----+----------+------------------------+----------------------+
| 54 |        6 |                      1 | MarketingTerritoryID |
| 53 |        6 |                      1 | PlaceTypeID          |
+----+----------+------------------------+----------------------+
2 rows in set (0.00 sec)

请解释为什么以下sql查询有效:

SELECT 
   table1.id
FROM table1
  LEFT JOIN table2 AS placeType
    ON table1.id = placeType.placeId
      AND placeType.dictionaryCode = 'PlaceTypeID'
  LEFT JOIN table2 AS region
    ON table1.id = region.placeId
      AND region.dictionaryCode  = 'MarketingTerritoryID'
GROUP BY region.dictionaryId
HAVING region.dictionaryId = MIN(1)

......和另一个

SELECT 
   table1.id
FROM table1
  LEFT JOIN table2 AS placeType
    ON table1.id = placeType.placeId
      AND placeType.dictionaryCode = 'PlaceTypeID'
  LEFT JOIN table2 AS region
    ON table1.id = region.placeId
      AND region.dictionaryCode  = 'MarketingTerritoryID'
GROUP BY region.dictionaryId, placeType.dictionaryId
HAVING region.dictionaryId = MIN(1)

返回sql错误: *Unknown column 'region.dictionaryId' in 'having clause'*

请注意,这两个查询之间的区别仅在于group子句:第二个查询也按 placeType.dictionaryId分组

这是来自sqlfiddle的代码:

  1. 首次查询http://sqlfiddle.com/#!9/46a85/7
  2. 第二次查询http://sqlfiddle.com/#!9/46a85/8

1 个答案:

答案 0 :(得分:0)

我已经向mysql团队报告了这个错误。这是链接:https://bugs.mysql.com/bug.php?id=82317

目前已经验证了状态。让我们看看他们会回答什么。