MySQL: 1055 Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column
group by有一個原則,就是select後面所有的列中,沒有使用聚合函式的列,必須出現在group by子句中。
group by子句中的注意事項:
1,不能使用別名(因為執行順序的原因)
2,除了函式欄位,select子句中出現的所有欄位都必須在group by中出現
only_full_group_by
MySQL 其實很早就添加了 only_full_group_by
這個 sql_mode
,但一直都作為可選項之一,並沒有強制預設。
然而,MySQL 5.7 之後,only_full_group_by
成為 sql_mode
的預設選項之一
這就會讓我們的一些慣性思維導致一系列的 SQL
only_full_group_by
這個 sql_mode 的唯一要求,就是所有的 select 欄位必須在 group by 欄位中,否則必須出現在 SQL Aggregate 函式中,反過來卻是非必須的
補充:
有用的 Aggregate 函式:
- AVG() - 返回平均值
- COUNT() - 返回行數
- FIRST() - 返回第一個記錄的值
- LAST() - 返回最後一個記錄的值
- MAX() - 返回最大值
- MIN() - 返回最小值
- SUM() - 返回總和
第一種解決方法:
select
product_id,any_value(shop_id),any_value(create_time),count(product_id) as total
tb_user_product
where
date_format(create_time,'%Y-%m-%d')=date_sub(curdate(),interval 1 day)
group by
product_id
第二種解決方法:
select
product_id,shop_id,create_time,count(product_id) as total
from
tb_user_product
where
date_format(create_time,'%Y-%m-%d')=date_sub(curdate(),interval 1 day)
group by