2015-10-09 58 views
0

我從我的數據庫檢索數據與此查詢:MYSQL選擇,加盟,金額和更新多個行

SELECT 
    users.id as id, 
    users.username as UserName, 
    users.wochenh as wochenh, 
    ROUND(DAY(LAST_DAY(NOW()- INTERVAL 1 MONTH))/7*users.wochenh,0) as monatsstunden, 
    ROUND(SUM(TIMESTAMPDIFF(MINUTE, start, end))/60,0) AS total, 
    users.uberh as OLD_VALUE, 
    ROUND(SUM(TIMESTAMPDIFF(MINUTE, start, end))/60,0) - ROUND(DAY(LAST_DAY(NOW()- INTERVAL 1 MONTH))/7*users.wochenh,0) AS ueberh, 
    ROUND(SUM(TIMESTAMPDIFF(MINUTE, start, end))/60,0) - ROUND(DAY(LAST_DAY(NOW()- INTERVAL 1 MONTH))/7*users.wochenh,0) + users.uberh AS NEW_VALUE 
    FROM time_entries 
    inner join users on users.id = time_entries.user_id 
    WHERE start BETWEEN DATE_FORMAT(NOW() - INTERVAL 1 MONTH, '%Y-%m-01 00:00:00') AND DATE_FORMAT(LAST_DAY(NOW() - INTERVAL 1 MONTH), '%Y-%m-%d 23:59:59') 
    GROUP BY user_id 

這使我有我的信息精細這樣的:

id UserName wochenh monatsstunden total OLD_VALUE ueberh NEW_VALUE 
#1 "3" "ph"  "32"  "137"  "168" "200"  "31" "231" 
#2 "4" "me"  "28"  "120"  "173" "164"  "53" "217" 
#3 "6" "dp"  "24"  "103"  "89" "-10"  "-14" "-24" 
#4 "12" "ab"  "10"  "43"   "26" "24"  "-17" "7" 
#5 "13" "fh"  "9"  "39"   "44" "25"  "5"  "30" 

現在我的問題是:如何在此查詢中將OLD_VALUE設置爲NEW_VALUE?

請幫忙!最好, 克里斯

+1

您正在尋找http://stackoverflow.com/questions/15209414/how-to-use-join-in-update-query – RubahMalam

+0

謝謝!這非常有幫助。 –

回答

0

得到它的工作:

UPDATE users u 
    JOIN (SELECT 
    users.id as id, 
    users.username as UserName, 
    users.wochenh as wochenh, 
    ROUND(DAY(LAST_DAY(NOW()- INTERVAL 1 MONTH))/7*users.wochenh,0) as monatsstunden, 
    ROUND(SUM(TIMESTAMPDIFF(MINUTE, start, end))/60,0) AS total, 
    users.uberh as OLD_VALUE, 
    ROUND(SUM(TIMESTAMPDIFF(MINUTE, start, end))/60,0) - ROUND(DAY(LAST_DAY(NOW()- INTERVAL 1 MONTH))/7*users.wochenh,0) AS ueberh, 
    ROUND(SUM(TIMESTAMPDIFF(MINUTE, start, end))/60,0) - ROUND(DAY(LAST_DAY(NOW()- INTERVAL 1 MONTH))/7*users.wochenh,0) + users.uberh AS NEW_VALUE 
    FROM time_entries 
    inner join users on users.id = time_entries.user_id 
    WHERE start BETWEEN DATE_FORMAT(NOW() - INTERVAL 1 MONTH, '%Y-%m-01 00:00:00') AND DATE_FORMAT(LAST_DAY(NOW() - INTERVAL 1 MONTH), '%Y-%m-%d 23:59:59') 
    GROUP BY user_id) e ON u.id = e.id 
    SET u.uberh = e.NEW_VALUE 
+0

你可以接受你自己的答案,以確保這個問題已經有了正確的答案。 – RubahMalam