我需要更新多個選擇的總和計算的字段。選擇部分工作,但我不能找到一種方法來更新用戶表更新查詢SUM多個選擇
user
+------+---------+
| id | total |
+------+---------+
| 1 | |
| 2 | |
unita
+------+-------+-----+
| id | uid | num |
+------+-------+-----+
| 1 | 1 | 25 |
| 1 | 2 | 10 |
unitb
+------+-------+-----+
| id | uid | num |
+------+-------+-----+
| 9 | 1 | 225 |
| 9 | 2 | 10 |
class
+------+--------+------+
| id | name | cost |
+------+--------+------+
| 1 | class1 | 100 |
| 9 | class9 | 500 |
SELECT uid, SUM(score) FROM (
SELECT unita.uid, SUM(class.cost * unita.num) AS cost FROM unita, class WHERE unita.id = class.id GROUP BY unita.uid
UNION
SELECT unita.uid, SUM(class.cost * unitb.num) AS cost FROM unitb, class WHERE unitb.id = class.id GROUP BY unitb.uid
) x GROUP BY uid
update命令應總結每個用戶
User 1: (25*100)+(225*500) = 115000
User 2: (10*100)+(10*500) = 6000
它這個可能一切代價1個SQL命令中。該單元表被鎖定,所以我不能做任何修改
只需添加'更新用戶u連接(您的選擇查詢,直到通過uid組)「y上的y.uid = u.uid set u.total = y.score'也給選擇部分的別名作爲'SELECT uid ,SUM(評分)作爲得分...' –
http://stackoverflow.com/questions/8057565/mysql-update-statement-inner-join-tables –
參見下面[鏈接]此鏈接[1] 希望它能幫助你。 [1]:http://stackoverflow.com/questions/1262786/mysql-update-query-based-on-select-query –