distinct 和order by 冲突解决方案

  • Post author:
  • Post category:其他

在新版的mysql5.7的版本中,如果DISTINCTorder by一起使用将会报3065错误,sql语句无法执行。最新的mysql5.7版本语法比之前5.6版本语法更加严格导致的。DISTINCT和order by都会对数据进行排序操作,所以会产生冲突。

SELECT
 DISTINCT a.title,a.tax_no
FROM
 order_invoice a
LEFT JOIN order_data b ON a.order_id = b.order_id
WHERE
 b.user_id = 166 and  a.state= 20 AND a.head_type=2 ORDER BY a.create_date desc limit 0,3

    解决方法一:

        使用group by 替代 distinct 的去重功能

SELECT c.title as name ,c.taxNo as taxNo FROM (
       SELECT
            a.title as title,a.tax_no as taxNo,max(a.id) as id
            FROM
                order_invoice a
            LEFT JOIN order_data b ON a.order_id = b.order_id
            WHERE
            b.user_id = 166 and  a.state= 20 AND a.head_type=2 GROUP BY a.title,a.tax_no ) c  ORDER BY c.id desc limit 0,3

解决方法二 :

 

        编辑mysql5.7的配置文件,添加配置 sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES,这段代码同时也可以解决mysql5.7中的group by导致的1055错误


版权声明:本文为Xhm1064原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。