Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Update same table as Select with Having and Group By

Tags:

mysql

I have a Select query which returns me the session IDs of all sessions that have a time less that 8 days old. It works great!

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

But, I am trying to update the table so that every record with the session ID that is less than 8 days old has its sessionStatus changed to 'closed'. From stackoverflow I know I can't update a table that I am also selecting from and that Having and Group By are agerate functions that make this more complex.

I tried this, but no dice!

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

I would really appreciate any help!

like image 405
user1412860 Avatar asked May 23 '12 14:05

user1412860


People also ask

Can we use GROUP BY in UPDATE query?

You can't issue an UPDATE statement using a group by. The point of using GROUP BY is to change the way that the result set is displayed to the user. When you have a GROUP BY statement you utilize the HAVING clause to filer the aggregated result set.

How do you UPDATE a table with data from the same table in SQL?

Update With Select Sub Query: Same Table. Thus, the simplest and straightforward way to update values from one table to another table is to use the UPDATE FROM SELECT statement. By using UPDATE FROM, you can avoid the complicated ways like cursors, table data type, temp table, etc.

How do I UPDATE multiple values at a time in MySQL?

UPDATE statement allows you to update one or more values in MySQL. Here is the syntax to update multiple values at once using UPDATE statement. UPDATE [LOW_PRIORITY] [IGNORE] table_name SET column_name1 = expr1, column_name2 = expr2, … [WHERE condition];


2 Answers

Here's the workaround I use in cases like this:

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;
like image 157
lanzz Avatar answered Oct 11 '22 09:10

lanzz


Try this one also -

UPDATE
  session s1
JOIN
  (SELECT MAX(sessionID) sessionID FROM session WHERE sessionStatus = 'open') s2
    ON s1.sessionID = s2.sessionID
SET
  s1.sessionStatus = 'closed';
like image 29
Devart Avatar answered Oct 11 '22 11:10

Devart