zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    54.施工方案第二季(最小生成树)
    53.FIB词链
    52.1076 排序
    最短路径:我的理解--SPFA算法
    POJ2187Beauty Contest
    CodeForces 279B Books
    SDUT 2527 斗地主
    HDU1020 Encoding
    POJ 2635 The Embarrassed Cryptographer
    POJ 1942 Paths on a Grid(组合数)
  • 原文地址:https://www.cnblogs.com/xing-29391/p/13403773.html
Copyright © 2011-2022 走看看