Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select last record and update it

I want to select the last record in the table and update its name.

UPDATE item 
SET name = (SELECT name FROM pds
            WHERE id = 9)
WHERE id=(SELECT id ORDER BY id DESC LIMIT 1);

However, when executing name is changed for all the records.

Tried also:

UPDATE item 
SET name = (SELECT name FROM pds
            WHERE id = 9)
WHERE id=(SELECT id FROM item ORDER BY id DESC LIMIT 1);
like image 584
Roberts Rakvics Avatar asked May 15 '16 15:05

Roberts Rakvics


People also ask

How do you update a specific record in MySQL?

MySQL UPDATE command can be used to update multiple columns by specifying a comma separated list of column_name = new_value. Where column_name is the name of the column to be updated and new_value is the new value with which the column will be updated.

How do I select the latest row in MySQL?

To select the last row, we can use ORDER BY clause with desc (descending) property and Limit 1.

How do I delete last record and give the latest records in MySQL?

The syntax is as follows: DELETE FROM yourTableName WHERE yourColumnName1=yourValue ORDER BY yourColumnName2 DESC LIMIT 1; The above syntax will delete last record (on condition) from a table. It sorts the column in descending order and choose the first element to delete.

How can I get last record with same ID in SQL?

SELECT * FROM test AS r WHERE r.ID in (SELECT ID FROM test WHERE status = 'Open'); But that will return all the records (ID) having "Open" in the database.


2 Answers

In MySQL you can apply order by and limit clauses to an update statement:

UPDATE item 
SET name = (SELECT name FROM pds
            WHERE id = 9)
ORDER BY id DESC
LIMIT 1
like image 83
Mureinik Avatar answered Sep 29 '22 15:09

Mureinik


Just use limit and order by:

update item
    set name = (select name from pds where id = 9)
    order by id desc
    limit 1;

Your second version should work . . . except MySQL probably generates a syntax error. Try:

UPDATE item i CROSS JOIN
       (SELECT MAX(i2.id) as maxid FROM item i2) mi
    SET i.name = (SELECT pds.name FROM pds WHERE pds.id = 9)
    WHERE i.id = mi.maxid;

The first version is syntactically correct, but it has no FROM clause, so it is using the id value from the outer query -- and just checking that the id is equal to itself. When using subqueries in the select or where clauses, always use qualified column names. I advise doing this all the time, but this is especially important for subqueries in these clauses.

like image 28
Gordon Linoff Avatar answered Sep 29 '22 16:09

Gordon Linoff