[英]How to update a SQL table based on record count no of another table?
I have two SQL tables named as Share
and Balance
. 我有两个名为
Share
和Balance
SQL表。 users
is common column in both table. users
是两个表中的公共列。 There are multiple rows/share for each user in Share
table. Share
表中的每个用户都有多个行/共享。
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. 我需要做的是通过在每个份额上添加1来更新“
Share
表中的“已paid
列,并且不需要在“ Balance
表的“ balance
列中添加该增加的计数。 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. 说,一个用户在“
Share
表中有3行/份额,如果我为每个份额添加+1,则在“ Balance
表的“ balance
列中需要添加3个现有余额。
I have written following sql statement. 我写了下面的sql语句。 It is updating
Share
table accordingly but Balance
table is updating wrong. 它正在相应地更新
Share
表,但Balance
表却更新错误。 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.