1. 程式人生 > >MySql update inner join!MySql跨表更新 多表update sql語句?如何將select出來的部分資料update到另一個表裡面?

MySql update inner join!MySql跨表更新 多表update sql語句?如何將select出來的部分資料update到另一個表裡面?

專案中,評論數,關注數等資料,是實時更新的。+1,-1 這種。

有的時候,可能統計不準確。

需要寫一個統計工具,更新校準下。

用Java寫SQL和函式,程式碼很清晰,方便擴充套件,但是太慢了。

為了簡單起見,只寫sql來統計,然後更新。(不想寫儲存過程)

語句如下:

#更新一個人的 關注數 followingCount

[sql] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. update behavior_redman_count a  
  2. innerjoin
  3. (  
  4. select memberId,count(*) as followingCount from behavior_follow 
    where type = 10  
  5. and isDelete=0 groupby memberId   
  6. )b   
  7. set a.followingCount =b.followingCount  
  8. where a.redmanId = b.memberId;  
save_snippets.png
update behavior_redman_count a
inner join
(
select memberId,count(*) as followingCount from behavior_follow where type = 10
and isDelete=0 group by memberId 
)b 
set a.followingCount =b.followingCount
where a.redmanId = b.memberId;




#MySQL不支援這種語法
[sql] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. update behavior_redman_count  
  2. set followingCount = b.followingCount  
  3. from
  4. (  
  5. selectcount(*) as followingCount from behavior_follow where type = 10 and memberId = 198  
  6. and isDelete=0  
  7. )b   
  8. where redmandId = a.memberId and a.memberId= 198;  
save_snippets.png
update behavior_redman_count
set followingCount = b.followingCount
from
(
select count(*) as followingCount from behavior_follow where type = 10 and memberId = 198
and isDelete=0
)b 
where redmandId = a.memberId and a.memberId= 198;


參考資料

1. Mysql跨表更新 多表update sql語句總結

http://www.jb51.net/article/32648.htm

2.如何將select出來的部分資料update到另一個表裡面?

http://bbs.csdn.net/topics/320233666