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

时间:2020-03-02 06:35:58

标签: mysql group-by average coalesce

我通过将两个表连接在一起来获取记录,即产品表将与评级表连接并获得具有平均评级的产品,但是不幸的是,它在实时服务器上不起作用,但是在本地主机上运行良好,所以我在下面进行了跟踪链接,但没有变化仍然出现相同的错误,所以最后我意识到这是查询问题,因为本地主机运行良好,如果我尝试以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

3 个答案:

答案 0 :(得分:1)

您需要在分组依据中添加所有未聚合的列

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

答案 1 :(得分:1)

使用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

答案 2 :(得分:0)

请在此处检查解决方案。设置系统变量,然后从系统变量中删除ONLY_FULL_GROUP_BY

Disable ONLY_FULL_GROUP_BY