问题是这个..
表就是这个..
+--------------------------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------------+---------+------+-----+---------+----------------+
| facility_map_id | int(10) | NO | PRI | NULL | auto_increment |
| facility_map_facility_id | int(10) | NO | MUL | NULL | |
| facility_map_listing_id | int(10) | NO | | NULL | |
+--------------------------+---------+------+-----+---------+----------------+
数据就是这个..
+-----------------+--------------------------+-------------------------+
| facility_map_id | facility_map_facility_id | facility_map_listing_id |
+-----------------+--------------------------+-------------------------+
| 248 | 1 | 18 |
| 259 | 1 | 19 |
| 206 | 1 | 20 |
| 244 | 1 | 21 |
| 249 | 2 | 18 |
| 207 | 2 | 20 |
| 208 | 3 | 20 |
| 245 | 3 | 21 |
| 260 | 4 | 19 |
| 261 | 5 | 19 |
| 246 | 6 | 21 |
| 250 | 7 | 18 |
| 247 | 8 | 21 |
+-----------------+--------------------------+-------------------------+
我运行此查询:
SELECT facility_map_listing_id
FROM facility_map
WHERE facility_map_facility_id IN(1, 2)
GROUP BY facility_map_listing_id
HAVING count(DISTINCT facility_map_facility_id) >= 2
得到这个..
+-------------------------+
| facility_map_listing_id |
+-------------------------+
| 18 |
| 20 |
+-------------------------+
2 rows in set (0.00 sec)
哪个是对的! - 但有人可以解释一下,为什么GROUP BY需要在声明中?
如果它是Isnt并且我运行相同的查询而忽略GROUP BY我得到..
+-------------------------+
| facility_map_listing_id |
+-------------------------+
| 18 |
+-------------------------+
1 row in set (0.00 sec)
任何人都可以向我解释一下吗?谢谢!
答案 0 :(得分:5)
如果没有group by
,像count
这样的聚合就可以作为整体使用。所以这个查询返回零行或一行:
SELECT facility_map_listing_id
FROM facility_map
WHERE facility_map_facility_id IN(1, 2)
HAVING count(DISTINCT facility_map_facility_id) >= 2
如果满足having
条件,它将返回一行,否则返回空集。
现在,使用group by,它会为having
的每个值评估facility_map_listing_id
条件。这可以返回尽可能多的行,因为有facility_map_listing_id
的不同值。
答案 1 :(得分:5)
答案 2 :(得分:1)
我们可以使用不带GROUP BY
子句的HAVING子句,但SELECT
列和HAVING
列应与聚合函数一起使用:
HAVING 通常与GROUP BY
子句一起使用,主要用于通过使用聚合函数来操作和过滤数据。 当不使用GROUP BY时,HAVING的行为类似于WHERE子句。
HAVING 为group by
子句设置条件,类似于设置select子句的条件的方式。