2017-05-08 64 views
0

我想更新取決於變量如表:SQL有條件更新情況

$number = 3; 

UPDATE Table1 m 
    SET m.col1 = 1 
    WHERE m.id IN (SELECT id From Table2 where other_id = m.other_id) 
ELSE 
    SET all remaining to 0 
UPDATE Table1 m SET m.col1 = 0 

因此,所有我想要的是,如果$數爲0的所有記錄爲0,如果$數量> 0,則該數量行需要在表1 注意要設置1:記錄需要最後一個記錄DESC ID限$數

編輯: 爲了更好的社區就是我需要的是,這我怎麼會成功地與PHP和SQL,但我完成它將需要運行2個單獨的查詢。

見PIC

正如你看到我使用兩個單獨的查詢我在想,如果它可以只用SQL來完成。 enter image description here

+3

編輯您的問題,並提供樣本數據和所需的結果。 –

回答

0

您可以使用相關子查詢做到這一點:

update Table1 m 
    set m.col1 = case 
    when exists(select 1 from Table2 where other_id = m.other_id) 
     then '1' 
     else '0' 
    end 

我不知道如果表走樣Table1 m與MySQL的作品。我知道它不適用於SQL服務器。所以,你可能需要將它這樣寫:

update Table1 
    set col1 = case 
    when exists(select 1 from Table2 m2 where m2.other_id = Table1.other_id) 
     then '1' 
     else '0' 
    end 

的技巧是,你使用case when ... then ... else ... end結構。相關的子查詢位於when ...部分。它會檢查Table2中是否存在相關行。

您也可以嘗試使用update-with-join技巧,因爲速度更快。不幸的是,我不能用我的SQL服務器來嘗試,因爲它具有不同的語法。它看起來像這樣:

UPDATE Table1 m 
LEFT JOIN Table2 m2 on (m.other_id = m2.other_id) 
SET m.col1 = CASE WHEN m2.other_id IS NULL THEN 0 ELSE 1 END