2012-11-29 61 views
2

我有一個表命名status_t:mysql的幫助更新行具有相同的值

**id** **page** **status** **locked**_by 
    1  0  2   0 
    1  1  2   0 
    1  2  2   0 
    2  0  0   0 
    2  1  2   0 
    2  2  2   0 

主鍵(ID,頁)。

在上面的例子,我想更新所有 行是有狀態的所有頁= 2

查詢應更新所有ID的行數= 1〜3的狀態所以該表將成爲

**id** **page** **status** **locked**_by 
    1  0  3   1 
    1  1  3   1 
    1  2  3   1 
    2  0  0   0 
    2  1  2   0 
    2  2  2   0 

我曾嘗試:

SELECT * FROM status_t AS t 
WHERE id IN 
(SELECT id FROM status WHERE status = 0) LIMIT 10 

上面的查詢獲取的行被更新,但我不能這樣做:

UPDATE status_t as S1 WHERE id IN 
(SELECT id FROM status_t WHERE status = 2) 
SET S1.status = 3, S1.locked_by = 1 

編輯:

上表只是一個例子。

我不想更新WHERE id = 1。我只想更新行,不管ID爲 的status = 2是否爲相同的id。 在上面的例子中,如果具有鍵(2,2)的行的狀態= 2,那麼它應該被更新。

+0

檢查我的答案這將更新表格,因爲你想 –

回答

1

這應該工作:

update status_t t 
join (
    select distinct id from status_t s 
    where status=2 and not exists (
     select 1 from status_t ss 
     where s.id=ss.id and s.status <> ss.status 
    ) 
) i on i.id = t.id 
set t.status = 3 

內部查詢選擇ID爲status的所有值都設置爲2的ID。它通過檢查tere沒有具有相同ID和不同狀態的行來實現此結果。

這是demo on sqlfiddle

+0

謝謝。我怎麼也可以申請一個限制? 我想至多更新N行 –

+0

@GiorgosKomnino超出限制的行應該發生什麼? – dasblinkenlight

+0

我認爲這個極限應該除以3。所以在上面的例子中,我只能放置限制3,6,9等。如果我把限制2,那麼它只會更新前兩行,然後最後(id = 1,page = 2)不會更新 –

0

下應該做的伎倆:

UPDATE status_t 
SET status = 3, locked_by = 1 
WHERE status = 2 

應該沒有必要使用子查詢,因爲WHERE應該可以直接在UPDATE語句中使用。

編輯:

我只注意到你只有對行的更新與ID = 1,不匹配的聲明「在上面的例子中,我想更新所有的所有頁面都狀態行= 2. . The rows where id = 2 , and status = 2`也會被我的查詢更新。

如果您只需要更新一個特定的ID,添加以下我查詢的末尾:

​​

0

試試這個::

UPDATE status_t SET status = 3, locked_by = 1 WHERE status = 2 

如果你想實現這在你的方式:

UPDATE 
status_t as S1 
INNER JOIN 
(
    SELECT keyword_id 
    FROM status_t WHERE status = 2 
) as tempStatus ON id= tempStatus.keyword_id 

SET S1.status = 3, S1.locked_by = 1 
0

試試這個

update status_t set staus=3 ,locked_by=1 
    where id=1 

update status_t set status=3 ,locked_by=1 
    where status=2 
0
UPDATE status_t SET status = 3, S1.locked_by = 1 WHERE id = 1 
1

試試這個:

UPDATE status_t a 
INNER JOIN (SELECT id FROM status_t WHERE STATUS = 2 GROUP BY id HAVING COUNT(*) = 3 LIMIT 1) AS b ON a.id = b.id 
SET a.status = 3, a.locked_by = 1; 

,只要你想對所有頁面都有這將更新數據狀態= 2

+0

@GiorgosKomnino使用我的答案你可以設置限制連續,它更新記錄,因爲你想 –

相關問題