2016-04-19 30 views
0

我有兩個表如何通過使用mysql中的更新從另一個表中獲取計數來增加一個表的計數?

一個是business_details

+--------------+--------------++--------------+ 
| msisdn  | total_counts || id   | 
+--------------+--------------++--------------+ 
| 919999999999 |   0 || 2323232 | 
| 918888888888 |   0 || 2323231 | 
| 917777777777 |   15 || 2323233 | 
+--------------+--------------++--------------+ 

,另一臺是:users_details

+--------------++--------------+ 
| msisdn  || id   | 
+--------------++--------------+ 
| 919999999999 || 2323232 | 
| 918888888888 || 2323231 | 
| 917777777777 || 2323233 | 
+--------------++--------------+ 

我想更新表 'business_details',並設置共有TOTAL_COUNTS = total_counts +(來自users_details業務的計數_details.msisdn = users_details.msisdn和business_details.id = users_details.id)

誰能幫助通過從另一個表匹配兩個條件遞增到一個表的計數?

回答

1

您的問題的基本答案是在update聲明中使用join

我打算猜測用戶表中的總計數是指行數。這需要聚合之前join

update business_details bd join 
     (select ud.msisdn, count(*) as cnt 
     from user_details ud 
     group by ud.msisdn 
     ) ud 
     on bd.msisdn = ud.msisdn 
    set bd.total_counts = bd.total_counts + ud.cnt; 
+0

Thanx的幫助:-) –

相關問題