I have two SQL tables named as Share
and Balance
. users
is common column in both table. There are multiple rows/share for each user in Share
table.
What I need to do is update paid
column from Share
table by adding 1 on each share and that added count no needs to be added in balance
column of Balance
table. Say, a user has 3 rows/shares in Share
table and if i add +1 for each share then in balance
column of Balance
table needs to add 3 with existing balance.
I have written following sql statement. It is updating Share
table accordingly but Balance
table is updating wrong. See the image below:
Update Share Set paid=paid + 1
Update Balance Set balance=balance + S.Paid
From balance B,share S Where B.users=S.users
Update Share Set paid=paid + 1
Update Balance Set balance=balance + (select count(S.Paid) From balance B,share S
Where B.users=S.users
group by s.users )
From balance B,share S Where B.users=S.users
--If increment is always +1 in share table then this query will work fine.
You could use two select.
For readblity is better the explicit join sintax
and if you use alias you should use the table alias in all the columns name
Update Share
Set paid=paid + 1;
Update Balance B
INNER JOIN (
select users, count(*) an num_count
from share
group by user
) t on t.users = B.users
Set B.balance=B.balance + t.num_count;
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.