問題是這樣的..瞭解GROUP BY語句的行爲
表是這樣的..
+--------------------------+---------+------+-----+---------+----------------+
| 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需要在聲明中?
,如果它不是,我運行相同的查詢而忽略了GROUP BY我得到..
+-------------------------+
| facility_map_listing_id |
+-------------------------+
| 18 |
+-------------------------+
1 row in set (0.00 sec)
任何一個可以解釋這樣對我?謝謝!
布里爾 - 解釋的事情完全。謝謝你的幫助! –