一. 使用過程
Query 1 ERROR: Expression #2 of SELECT list is not in GROUP BY clause
and contains nonaggregated column 'ai.ln_owners.name' which is not functionally dependent on columns
in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
SELECT
`ln_housing_id`,
`name`
FROM
`ln_owners`
ORDER BY
`id` DESC
GROUP BY
`ln_housing_id`
- 這種又會出現什么樣的錯誤呢,我們看下 【這次是語法錯誤】:
Query 1 ERROR: You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'GROUP BY
`ln_housing_id`' at line 8
二、 我們該如何正確使用 GroupBy
和 OrderBy
呢
SELECT
ln_housing_id,
aid,
lasted
FROM (
SELECT
`ln_housing_id`,
ANY_VALUE(`id`) AS aid,
ANY_VALUE(`updated_at`) AS lasted
FROM
`ln_owners`
GROUP BY
`ln_housing_id`) AS tb
ORDER BY
tb.lasted DESC
-
groupBy
里面子句查詢如果在你開啟 sql_mode=only_full_group_by
聚合列索引檢查,就會出錯
- 開啟的話,我們使用 ANY_VALUE('id') 聚合一下其他列 ,然后通過子查詢的派生表 再去外層進行降序排列
- 如果groupBy 的字段是主鍵(primaryKey) 或者 唯一不為 NULL 列,這個是可以不用聚合列的,可以查詢所有,因為列字段沒有可選性