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
       from
               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
             product_id,shop_id,create_time


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM