group by error:这与sql_mode = only_full_group_by不兼容

时间:2018-02-18 10:58:55

标签: mysql

我有两个表order和order_detail

order
id   |  total   |  date
------------------------
 1      3500      2018-02-10
 2      1000      2018-02-18

order_detail
id  |  order_id  |  item_id  |  quantity
-------------------------------------------------
 1          1            4         20
 2          1            6         10
 3          2            3         50

我正在努力实现

orderCount  |  itemCount  | totalAmount  
----------------------------------------
  2               80            4500

我已经写了这个查询来提取最后30天的摘要:

select COUNT(*) as orderCount  
     , (select SUM(od.quantity) 
          from order_detail od 
         where od.order_id = o.id

       ) as itemCount
     , SUM(o.total) as totalSum 
  from order o 
 WHERE DATE_SUB(CURDATE(),INTERVAL 30 DAY) <= o.date

此查询在本地mysql数据库中正常工作

但在生产服务器中,它会产生以下错误:

#1140 - In aggregated query without GROUP BY, expression #2 of SELECT list contains nonaggregated column 'databaseb.o.id'; this is incompatible with sql_mode=only_full_group_by

2 个答案:

答案 0 :(得分:0)

第二栏:

 (select SUM(od.quantity) 
      from order_detail od 
     where od.order_id = o.id
   ) as itemCount

不是聚合值;它是子查询的结果(恰好产生聚合值,但这是无关紧要的。)

您必须添加:

group by 2

要使您的查询符合sql_mode=only_full_group_by

显然,您的本地数据库没有设置sql_mode=only_full_group_by

我怀疑你只想加入:

select COUNT(*) as orderCount  
  , SUM(od.quantity) as itemCount
  , SUM(o.total) as totalSum 
from order o 
left join order_detail od on od.order_id = o.id
WHERE DATE_SUB(CURDATE(),INTERVAL 30 DAY) <= o.date

答案 1 :(得分:0)

要实现您的欲望输出,您可以在查询

下使用
select sum(od.quantity) as itemCount,
sum(o.total) as totalAmount,
count(distinct(o.id)) as orderCount
from order_detail od
left join `order` o 
on od.id=o.id ;