MySQL查询错误:SELECT列表不在GROUP BY子句中,并且包含未聚合的列,与sql_mode = only_full_group_by不兼容

问题描述 投票:0回答:1

我通过将两个表连接在一起来获取记录,即产品表将与评级表连接并获得具有平均评级的产品,但是不幸的是,它无法在实时服务器上运行,但是在本地主机上运行良好,因此我在下面的链接中进行了跟踪但是没有变化仍然出现相同的错误,所以最后我意识到这是查询问题,因为本地主机运行良好,如果我尝试以sql模式进行更改,则在实时mysql服务器并显示preveliges限制的情况下是不允许的,那么需要更改查询才能正确获得结果。

product

id     product_name    keyword

1        A               xyz
2        B               abc
3        C               aaa
4        D               abc

rating

id      product_id    rating  

1          2             2
2          2             4
3          1             2
4          4             3
5          2             3
6          2             4

MySQL查询:

select p.pid,
       p.product_name, 
       COALESCE(ROUND(AVG(r.rating), 1), 0) as avgRate 
from product p 
left join rating r on r.product_id=p.id  
WHERE (LOWER(p.product_name) LIKE '%a%'  
   OR LOWER(p.keyword) LIKE '%abc%' )
GROUP BY p.product_id

引荐链接:

Error related to only_full_group_by when executing a query in MySql

#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by

mysql group-by average coalesce
1个回答
0
投票
您需要在分组依据中添加所有未聚合的列

select p.pid,p.product_name, COALESCE(ROUND(AVG(r.rating), 1), 0) as avgRate from product p left join rating r on r.product_id=p.id WHERE (LOWER(p.product_name) LIKE '%a%' OR LOWER(p.keyword) LIKE '%abc%' ) GROUP BY p.pid,p.product_name


0
投票
使用ANY_VALUE()功能:

select ANY_VALUE(p.pid) pid, ANY_VALUE(p.product_name) product_name, COALESCE(ROUND(AVG(r.rating), 1), 0) as avgRate from product p left join rating r on r.product_id=p.id WHERE ( LOWER(p.product_name) LIKE '%a%' OR LOWER(p.keyword) LIKE '%abc%' ) GROUP BY p.product_id

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