简体   繁体   中英

UPDATE VALUE IN MYSQL MARIA DB WITH JOIN

I am trying to change the value of a column table with a sum function, this is my code:

For example 
c.total = (10-2-3) - (3) 
c.total = 2

update tabC c 
JOIN tabB b ON b.c_id = c.id 
set c.total = (c.v1 - c.v2 - c.v3) - IF(sum(b.payment) is not null, sum(b.payment), 0) 
where c.id= 983;

but I get the following error:

ERROR 1111 (HY000): Invalid use of group function

I think the error is sum, but how can I solve that?

Thanls in advance

You need to join with a subquery that uses GROUP BY .

UPDATE tabC c
LEFT JOIN (
    SELECT c_id, SUM(payment) AS total_payment
    FROM tabB
    GROUP BY c_id) AS b ON b.c_id = c.id
SET c.total = (c.v1 - c.v2 - c.v3) - IFNULL(b.total_payment, 0)
WHERE c.id = 983

You should usee a nested subquery whit aggregated resutl for join

  update tabC c 
  JOIN  (
    select   c_id, ifnull(sum(payment),0) tot_payment
    from tabB
    group by c_id
  ) b ON b.c_id = c.id 
  set c.total = (c.v1 - c.v2 - c.v3) - b.tot_payment 
  where c.id= 983;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM