我在更新连接表时遇到问题。我已经成功选择了预期的结果,但当我尝试更新时总是收到错误。
选择查询
select sale_id, price,cONVERT(sum(price) , decimal(10,2)) as average, s.total from sale_items i
JOIN sales s ON s.id = i.sale_id
where s.currency = 'USD'
and s.currency_total != 0
and s.`deleted_at` is null
and i.`deleted_at` is null
group by s.id
having s.total <> average;
更新我尝试过的查询
UPDATE sale_items i
JOIN sales s ON s.id = i.sale_id
SET i.price=(i.price / (s.total/s.currency_total)), i.total=(i.total / (s.total/s.currency_total)), i.total_tax=(i.total_tax / (s.total/s.currency_total))
where s.currency = 'USD'
and s.currency_total != 0
and s.`deleted_at` is null
and i.`deleted_at` is null
group by s.id
having s.total <> average;
错误:在“group by s.id具有s.total <>average”附近使用的语法
最佳答案
在 5.6 中,根据 UPDATE 的手册页,多表更新有限制,包括没有 ORDER BY
平均值
仅存在于您的SELECT
查询中,未在更新查询中定义。
您需要包含一个扩展您的 where 的子查询,例如:
UPDATE sale_items i
JOIN sales s ON s.id = i.sale_id
SET i.price=(i.price / (s.total/s.currency_total)), i.total=(i.total / (s.total/s.currency_total)), i.total_tax=(i.total_tax / (s.total/s.currency_total))
where s.currency = 'USD'
and s.currency_total != 0
and s.`deleted_at` is null
and i.`deleted_at` is null
and s.total <> (select sum(price) from sale_items WHERE sale_id = s.id AND ...)`
关于Mysql 使用 join、group by 和having 子句更新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58760172/