0

I want to select a group of data from database by using the code below.

SELECT * FROM History INNER JOIN (SELECT MAX(id) as id FROM History GROUP BY home_id) last_updates ON last_updates.id = History.id

And the result, i get the group of data. Then i want to update field on the table based on the group of data and i use below code.

UPDATE History SET status = '0' WHERE (SELECT * FROM History INNER JOIN (SELECT MAX(id) as id FROM History GROUP BY home_id) last_updates ON last_updates.id = History.id)

I think my sql update code is correct, but i got

Error: Operand should contain 1 column(s).

Is there anything i need to change?

Malca
  • 123
  • 2
  • 11

1 Answers1

1

Try an update self join:

UPDATE History h1
INNER JOIN
(
    SELECT home_id, MAX(id) AS max_id
    FROM History
    GROUP BY home_id
) h2
    ON h1.home_id = h2.home_id AND
       h1.id = h2.max_id
SET
    h1.status = 0;

This assumes that you want to zero out the status of every record per home_id group having the max id value.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360