简体   繁体   中英

Why is my UPDATE query updating all rows?

I am trying to update the row most recently added to my table by adding a WHERE clause and selecting the MAX 'dressingID' which is my primary key.

The function is working however it is returning every row instead of just the row with the largest ID.

Here is the query:

UPDATE Dressing set dressingCode='111' WHERE dressingID=(SELECT MAX(dressingID))

Table Name = Dressing

Primary Key = dressingID

I am trying to get a number from a QR code and pass to to the latest entry into the table, however it is updating every row for some reason, any help would be appreciated. Cheers!

You need to reference table:

UPDATE Dressing set dressingCode='111' 
WHERE dressingID=(SELECT d FROM ((SELECT MAX(dressingID) AS d FROM Dressing)) s);
                  -- forced materialization

db<>fiddle demo

MariaDB 10.3:

UPDATE Dressing set dressingCode='111' 
WHERE dressingID=(SELECT MAX(dressingID) AS d FROM Dressing);

db<>fiddle demo

Related: You can't specify target table for update in FROM clause


Original query has A=MAX(A) condition for single row:

UPDATE Dressing set dressingCode='111' 
WHERE dressingID=(SELECT MAX(Dressing.dressingID))
<=>
UPDATE Dressing set dressingCode='111' 
WHERE dressingID=Dressing.dressingID
-- always true for non-nullable dressingID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM