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);
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.
To select the last row, we can use ORDER BY clause with desc (descending) property and Limit 1.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With