• 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

  • 相关阅读:
    学习进度三
    开课博客之个人介绍
    个人作业--数组
    学习进度二
    开学第一次测试
    实现点击不同的按钮加载不同的css
    Web存储
    HTML5(常用的表单控件)
    JS(获得当前时间并且用2015-01-01格式表示)
    JS(event事件)
  • 原文地址:https://www.cnblogs.com/xing-29391/p/13403773.html
Copyright © 2020-2023  润新知