2012-05-23 67 views
3

我有一個選擇查詢,它返回所有會議的時間少於8天的會話ID。它很棒!MySQL更新相同的表作爲選擇具有和組

SELECT sessionID FROM session WHERE sessionStatus = 'open' GROUP BY sessionID HAVING MAX(refTime) <= 8; 

但是,我想更新表,以便與會話ID的所有記錄小於8天大有sessionStatus變更爲「關閉」。從stackoverflow我知道我不能更新表,我也選擇,並有分組是比較年齡功能,使這更復雜。

我試過了,但沒有骰子!

UPDATE session 
SET sessionStatus='closed' 
WHERE sessionID = (select * from (SELECT MAX(sessionID) FROM session where sessionStatus = 'open') as t); 

我真的很感謝任何幫助!

+0

你得到任何錯誤? –

+0

請嘗試此解決方案: [http://stackoverflow.com/questions/8127257/mysql-update-subset-having/22638878#22638878][1] 問候 彼得 [1 ]:http://stackoverflow.com/questions/8127257/mysql-update-subset-having/22638878#22638878 –

回答

2

這裏是我的情況下使用這樣的解決方法:

CREATE TEMPORARY TABLE tempsessions AS SELECT MAX(sessionID) AS sessionID FROM session where sessionStatus = 'open'; 
UPDATE session SET sessionStatus = 'closed' WHERE sessionID IN (SELECT sessionID FROM tempsessions); 
DROP TEMPORARY TABLE tempsessions; 
+0

它的工作原理!非常感謝! – user1412860

2

嘗試這一個也 -

UPDATE 
    session s1 
JOIN 
    (SELECT MAX(sessionID) sessionID FROM session WHERE sessionStatus = 'open') s2 
    ON s1.sessionID = s2.sessionID 
SET 
    s1.sessionStatus = 'closed';