MySQL更新与选择有和分组相同的表

时间:2012-05-23 14:27:10

标签: mysql

我有一个Select查询,它返回时间少于8天的所有会话的会话ID。它很棒!

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

但是,我正在尝试更新表,以便会话ID小于8天的每条记录都将其sessionStatus更改为“已关闭”。从stackoverflow我知道我无法更新我也从中选择的表,并且Having和Group By是使得这更复杂的agerate函数。

我尝试了这个,但没有骰子!

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

我真的很感激任何帮助!

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:2)

也尝试这个 -

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