1 回答

TA貢獻(xiàn)1866條經(jīng)驗(yàn) 獲得超5個贊
主要取自解決有關(guān) ONLY_FULL_GROUP_BY SQL 模式的查詢失敗。一篇很棒的文章。
解釋
從 MySQL 5.7 開始,他們使語法更加嚴(yán)格,以阻止運(yùn)行語義上不正確的查詢。調(diào)用一個特定的新規(guī)則ONLY_FULL_GROUP_BY
,它可以防止您在使用 GROUP BY 子句時出錯。
一個容易理解的例子是這樣的:
假設(shè)我們想從此表中計算網(wǎng)站上最受歡迎的頁面:
+----+--------------------+---------+---------------------+
| id | page_url? ? ? ? ? ?| user_id | ts? ? ? ? ? ? ? ? ? |
+----+--------------------+---------+---------------------+
|? 1 | /index.html? ? ? ? |? ? ? ?1 | 2019-04-17 12:21:32 |
|? 2 | /index.html? ? ? ? |? ? ? ?2 | 2019-04-17 12:21:35 |
|? 3 | /news.php? ? ? ? ? |? ? ? ?1 | 2019-04-17 12:22:11 |
|? 4 | /store_offers.php? |? ? ? ?3 | 2019-04-17 12:22:41 |
|? 5 | /store_offers.html |? ? ? ?2 | 2019-04-17 12:23:04 |
|? 6 | /faq.html? ? ? ? ? |? ? ? ?1 | 2019-04-17 12:23:22 |
|? 7 | /index.html? ? ? ? |? ? ? ?3 | 2019-04-17 12:32:25 |
|? 8 | /news.php? ? ? ? ? |? ? ? ?2 | 2019-04-17 12:32:38 |
+----+--------------------+---------+---------------------+
你可以簡單地寫:
SELECT page_url, user_id, COUNT(*) AS visits?
? ? -> FROM web_log?
? ? -> GROUP BY page_url ORDER BY COUNT(*) DESC;
并得到如下結(jié)果:
+-------------------+---------+--------+
| page_url? ? ? ? ? | user_id | visits |
+-------------------+---------+--------+
| /index.html? ? ? ?|? ? ? ?1 |? ? ? 3 |
| /news.php? ? ? ? ?|? ? ? ?1 |? ? ? 2 |
| /store_offers.php |? ? ? ?3 |? ? ? 2 |
| /faq.html? ? ? ? ?|? ? ? ?1 |? ? ? 1 |
+-------------------+---------+--------+
但該列代表什么user_id?如果你仔細(xì)想想,它的內(nèi)容是完全隨機(jī)的。
您需要將其包含在 group_by 子句中,或者將其從選擇中排除(或者以其他方式將其包含在聚合函數(shù)中,例如count、min、max等)
所以對我來說,我需要在我的選擇中包含其他非聚合列:
select `events`.`listing_id`, `events`.`date`, `events`.`listing_name`, count(*) as number_sold?
from `events`?
where `events`.`date` >= "2020-07-14"
group by `events`.`listing_id`, `events`.`date`, `events`.`listing_name`
order by `events`.`date` asc
在我的情況下,這給出了預(yù)期的數(shù)據(jù)集。
- 1 回答
- 0 關(guān)注
- 189 瀏覽
添加回答
舉報