我用WAMP服务器在我的windows PC上使用MySQL 5.7.13
我的问题是在执行这个查询时
SELECT *
FROM `tbl_customer_pod_uploads`
WHERE `load_id` = '78' AND
`status` = 'Active'
GROUP BY `proof_type`
我总是得到这样的错误
SELECT列表中的表达式#1不在GROUP BY子句中,包含未聚合的列returntr_prod.tbl_customer_pod_uploads。id',它不依赖于GROUP BY子句中的列;这与sql_mode=only_full_group_by不兼容
你能告诉我最好的解决办法吗?
我需要这样的结果
+----+---------+---------+---------+----------+-----------+------------+---------------+--------------+------------+--------+---------------------+---------------------+
| id | user_id | load_id | bill_id | latitude | langitude | proof_type | document_type | file_name | is_private | status | createdon | updatedon |
+----+---------+---------+---------+----------+-----------+------------+---------------+--------------+------------+--------+---------------------+---------------------+
| 1 | 1 | 78 | 1 | 21.1212 | 21.5454 | 1 | 1 | id_Card.docx | 0 | Active | 2017-01-27 11:30:11 | 2017-01-27 11:30:14 |
+----+---------+---------+---------+----------+-----------+------------+---------------+--------------+------------+--------+---------------------+---------------------+
For the query to be legal in SQL92, the name column must be omitted from the select list or named in the GROUP BY clause.
SQL99 and later permits such nonaggregates per optional feature T301 if they are functionally dependent on GROUP BY columns: If such a relationship exists between name and custid, the query is legal. This would be the case, for example, were custid a primary key of customers.
MySQL 5.7.5 and up implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them.
via MySQL :: MySQL 5.7 Reference Manual :: 12.19.3 MySQL Handling of GROUP BY
你可以用下面的命令改变sql模式来解决这个问题:
SET GLOBAL sql_mode=(SELECT (@@sql_mode,'ONLY_FULL_GROUP_BY', "));
和…记得重新连接数据库!!
当MySQL的only_full_group_by模式被打开时,这意味着严格的ANSI SQL规则将在使用GROUP BY时应用。对于你的查询,这意味着如果你对proof_type列进行GROUP BY,那么你只能选择两件事:
proof_type列,或者
任何其他列的聚合
通过其他列的“聚合”,我指的是对另一列使用诸如MIN()、MAX()或AVG()之类的聚合函数。所以在你的情况下,下面的查询是有效的:
SELECT proof_type,
MAX(id) AS max_id,
MAX(some_col),
MIN(some_other_col)
FROM tbl_customer_pod_uploads
WHERE load_id = '78' AND
status = 'Active'
GROUP BY proof_type
我在SO上看到的绝大多数MySQL GROUP BY问题都关闭了严格模式,所以查询正在运行,但结果不正确。在您的情况下,查询根本不会运行,迫使您考虑真正想要做什么。
注意:ANSI SQL扩展了GROUP BY中允许选择的内容,也包括了功能上依赖于所选列的列。函数依赖的一个例子是按表中的主键列分组。由于保证主键对于每条记录都是唯一的,因此任何其他列的值也将确定。MySQL是允许这样做的数据库之一(SQL Server和Oracle不AFAIK)。
在我的例子中,这是我的旧sql_mode
sql_mode="ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"
您可以使用
show variables like "sql_mode";
然后我把它设置成这样
SET sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';