2013-07-14 76 views
1

我目前對兩個數據庫有兩個查詢。第一組的所有值設置爲0對於給定的USER_ID和秒更新每個用戶的1在兩個不同的WHERE條件下更新MySQL中的兩個表

UPDATE table_1 
JOIN table_2 ON table_1.user_id = table_2.user_id 
SET table_1.value = 0, 
table_2.total_value = 0 
WHERE table_2.user_id = %s AND table_1.user_id =%s 

UPDATE table_1 
JOIN table_2 ON table_1.user_id = table_2.user_id 
SET table_1.value = 555, 
table_2.total_value =1555 
WHERE table_1.rank =1 

我想他們整合到一起的等級,這會是可能的..?

+1

如果有2個獨立的數據庫,答案是否定的。他們必須在同一個數據庫中。 – edwardmp

回答

1
UPDATE table_1 
JOIN table_2 ON table_1.user_id = table_2.user_id 
SET table_1.value = case when table_2.user_id = %s AND table_1.user_id =%s 
         then 0 
         else table_1.value 
        end, 
    table_1.value = case when table_1.rank =1 then 555 else table_1.value end, 
    table_2.total_value = case when table_2.user_id = %s AND table_1.user_id =%s 
           then 0 
           else table_2.total_value 
          end, 
    table_2.total_value = case when table_1.rank =1 then 1555 else table_2.total_value end 
WHERE 
(
    table_2.user_id = %s AND table_1.user_id =%s 
) 
OR table_1.rank =1 
0

您可以有CASE語句來設置列上的值。

UPDATE table_1 
     INNER JOIN table_2 
      ON table_1.user_id = table_2.user_id 
SET  table_1.value =  CASE WHEN table_2.user_id = %s AND table_1.user_id = %s THEN 0 
           WHEN table_1.rank = 1 THEN 555 
           ELSE table_1.value 
          END, 
     table_2.total_value = CASE WHEN table_2.user_id = %s AND table_1.user_id = %s THEN 0 
            WHEN table_1.rank = 1 THEN 1555 
            ELSE table_1.value 
           END 
WHERE (table_2.user_id = %s AND table_1.user_id = %s) OR 
     (table_1.rank = 1) 
相關問題