如何解决“ORDER BY子句不在SELECT列表中”导致MySQL 5.7使用SELECT DISTINCT和ORDER BY

问题描述 投票:11回答:5

我安装了新的Ubuntu,我的代码遇到了MySQL问题。

( ! ) Warning: PDOStatement::execute(): SQLSTATE[HY000]: General error: 3065 
Expression #2 of ORDER BY clause is not in SELECT list, references column 'clicshopping_test_ui.p.products_date_added' which is not in SELECT list; this is incompatible with DISTINCT 
in /home/www//boutique/includes/OM/DbStatement.php on line 97s

看来MySQL 5.7不允许这样的请求:

select .... distinct with  order by rand(), p.products_date_added DESC

如果我使用它,它的工作原理:

select distinct .... with  order by rand(), 

如何解决这种情况?

我在PHP中的SQL请求

 $Qproduct = $OSCOM_PDO->prepare('select distinct p.products_id,
            p.products_price
            from :table_products p left join :table_specials s on p.products_id = s.products_id
            where products_status = :products_status
            and products_view = :products_view
            and p.products_archive = :products_archive
            order by rand(),
            p.products_date_added DESC
            limit :products_limit');
                  $Qproduct->bindInt(':products_status', 1);
                  $Qproduct->bindInt(':products_view', 1);
                  $Qproduct->bindInt(':products_archive', 0);
                  $Qproduct->bindInt(':products_limit', 
                  (int)MODULE_FRONT_PAGE_NEW_PRODUCTS_MAX_DISPLAY);
php mysql
5个回答
26
投票

如果您拥有对服务器的控制权并且您正在运行遗留代码而无法轻松更改,则可以通过运行查询来adjust the SQL mode of the server并在启动期间删除“only_full_group_by”

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));'

或者将sql_mode=''添加到您的my.cnf文件中。

如果你有可能,最好更改你的代码,但如果没有,这将禁用该警告。


1
投票

要解决此问题,请打开以下文件:

/etc/mysql/mysql.conf.d/mysqld.cnf

并在[mysqld]块下添加以下行

sql-mode=""

0
投票

试试这个:

    SELECT p.products_id,  p.products_price  
      FROM :table_products p
 LEFT JOIN :table_specials s on p.products_id = s.products_id 
     WHERE
           products_status = :products_status AND
           products_view = :products_view AND
           p.products_archive = :products_archive
  ORDER BY rand(),  p.products_date_added DESC
  GROUP BY p.products_id,p.products_price 
     LIMIT :products_limit

0
投票

使用MAMP PRO

您无法直接编辑my.cnf文件。您必须使用MAMP PRO界面编辑my.cnf文件。在菜单中,转到文件>编辑模板> MySQL> my.cnf。然后在sql_mode=''键下添加[mysqld]


0
投票

如果你有phpMyAdmin:

1 - 转到“变量”选项卡

2搜索标签“sql模式”

3编辑内容并删除模式:“ONLY_FULL_GROUP_BY”

4,保存

注意:不要忘记验证逗号分隔符


0
投票

rapaelec的答案对我有用(谢谢,因为我找不到mysql.conf文件!)。但是别忘了去phpmyadmin的主页看变量标签。

© www.soinside.com 2019 - 2024. All rights reserved.