组功能的使用无效,但没有GROUP BY

时间:2015-04-14 06:46:31

标签: mysql group-by

我正在尝试运行此查询:

UPDATE `ps_category_lang` cl 
  LEFT JOIN ps_product_shop p 
    ON cl.id_category=p.id_category_default 
     AND cl.id_shop=p.id_shop 
     AND p.available_for_order =1 
     AND p.visibility != 'none' 
  LEFT JOIN ps_specific_price sp 
    ON p.id_product=sp.id_product 
    AND ((sp.`from` = '0000-00-00 00:00:00' OR NOW() >= sp.`from`) 
    AND (sp.`to` = '0000-00-00 00:00:00' OR NOW() <= sp.`to`)) 
    AND (sp.id_shop=0 OR sp.id_shop=p.id_shop)
  SET cl.meta_title=CONCAT(
    SUBSTRING_INDEX(
      TRIM(cl.`meta_title`),
      'från', 
      1
    ), 
    'från ', 
    FORMAT(
      ROUND(
        min(p.price-IF(sp.reduction>0,sp.reduction, 0)
      ) * 
      (SELECT conversion_rate 
         FROM ps_currency 
         WHERE iso_code='SEK' 
           AND deleted=0
      )
    ),
    0, 
   'sv_SE'),
   ' kr.',
   SUBSTRING_INDEX(cl.`meta_title`, ' kr.', -1)
   )
   WHERE cl.`id_lang` = 7 
     AND cl.meta_title LIKE '% från%' 
     AND cl.meta_title LIKE '% kr.%' 
     AND p.available_for_order= 1 

但它给出了错误'#1111 - 无效使用组功能',尽管没有分组依据。为什么会出现这个错误?

2 个答案:

答案 0 :(得分:0)

您无法在UPDATE查询中直接使用聚合函数 - 并且任何使用聚合函数的查询(例如min)都会添加隐式group by

  

如果在不包含GROUP BY的语句中使用组函数   子句,它相当于对所有行进行分组

manual ref

并将其简化为简单的例子:

update the_table set value = min(value)

将生成您的`ERROR 1111(HY000):无效使用组功能。

要完成该查询的目的,您需要这样做:

update the_table set value = (select min(value) from the_table)

这意味着您的错误来源是查询的这一特定部分min(p.price-IF(sp.reduction>0,sp.reduction, 0),并且为了解决这个问题,您需要将其转换为为您计算值的子查询。 / p>

答案 1 :(得分:0)

使用像这样的临时表来解决它:

CREATE TEMPORARY TABLE tmp SELECT id_category_default, MIN(p.price-IF(sp.reduction>0,sp.reduction, 0)) AS minprice FROM ps_product_shop p LEFT JOIN ps_specific_price sp ON p.id_product=sp.id_product AND ((sp.`from` = '0000-00-00 00:00:00' OR NOW() >= sp.`from`) AND (sp.`to` = '0000-00-00 00:00:00' OR NOW() <= sp.`to`)) AND (sp.id_shop=0 OR sp.id_shop=p.id_shop) WHERE p.available_for_order= 1 GROUP BY p.id_category_default;
UPDATE `ps_category_lang` cl LEFT JOIN ps_product_shop p ON cl.id_category=p.id_category_default AND cl.id_shop=p.id_shop AND p.available_for_order =1 AND p.visibility != 'none' LEFT JOIN ps_specific_price sp ON p.id_product=sp.id_product AND ((sp.`from` = '0000-00-00 00:00:00' OR NOW() >= sp.`from`) AND (sp.`to` = '0000-00-00 00:00:00' OR NOW() <= sp.`to`)) AND (sp.id_shop=0 OR sp.id_shop=p.id_shop) LEFT JOIN tmp t on t.id_category_default=p.id_category_default AND t.minprice is not null
SET cl.meta_title=CONCAT(SUBSTRING_INDEX(TRIM(cl.`meta_title`),'från', 1), 'från ',FORMAT(ROUND(t.minprice)*(SELECT conversion_rate FROM ps_currency WHERE iso_code='SEK' AND deleted=0),0, 'sv_SE'),' kr.',SUBSTRING_INDEX(cl.`meta_title`, ' kr.', -1))
WHERE cl.`id_lang` = 7 AND cl.meta_title LIKE '% från%' AND cl.meta_title LIKE '% kr.%' AND p.available_for_order= 1 ;
DROP TEMPORARY TABLE tmp