Mysql 使用 join、group by 和 having 子句更新 table
Mysql update table with join, groupby and having caluse
我加入的更新有问题 table。我已经成功 select 得到了预期的结果,但是当我尝试更新时总是出现错误。
Select查询
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 having s.total <> average'
附近使用的语法
在 5.6 中,根据 UPDATE 的手册页,多 table 更新有限制,包括没有 ORDER BY
average
仅存在于您的 SELECT
查询中,未在更新查询中定义。
您需要包含一个扩展您所在位置的子查询,例如:
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 ...)`
我加入的更新有问题 table。我已经成功 select 得到了预期的结果,但是当我尝试更新时总是出现错误。
Select查询
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 having s.total <> average'
附近使用的语法在 5.6 中,根据 UPDATE 的手册页,多 table 更新有限制,包括没有 ORDER BY
average
仅存在于您的 SELECT
查询中,未在更新查询中定义。
您需要包含一个扩展您所在位置的子查询,例如:
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 ...)`