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

新手上路,请多包涵

我安装了新的 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);

原文由 kurama 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
1 个回答
  1. 您可以按上述方式运行:
 SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

但是如果你重新启动你的服务器,你可能需要重新运行它。


  1. 您可以更新 mysql 服务器配置:
  • 在 Windows 上, ${MY_SQL_HOME}/my.cnf (或 my.ini
  • 在 Linux 上,以下之一: etc/my.cnf/etc/mysql/my.cnf 、 /usr/etc/my.cnf ~/.my.cnf
 [mysqld]

# RESOLVE order-by-clause-is-not-in-select-list by removing ONLY_FULL_GROUP_BY from the sql-mode list
sql-mode="STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"

原文由 Paul EDANGE 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题