简体   繁体   中英

SQL (and Javax.Persistence.Query.ExecuteQuery) How to use UPDATE with WHERE-IN and AND

I'm trying to make a SQL statement that updates specific rows in the table's "status" column from 'NOT OK' to 'OK', but only for rows with the supplied ID and status.

Data in table (table1.id, table1.status) = [ID1, PENDING], [ID2, NOT OK], [ID3, NOT OK]

A list of IDs will be passed from java to the "in ()" part, I only have the ID and no status data. Notice that ID1's status that is not 'NOT OK'.

The code I have so far;

UPDATE table1
SET table1.status = 'OK'
WHERE table1.status = 'NOT OK' AND table1.id in ('ID1', 'ID2', 'ID3')

If the list inside the brackets contains all IDs with 'NOT OK', it'll make the changes to all the IDs in the brackets. But if one of the ID contains a different status, it won't make any changes.

The statement should ignore ID1 because its status isn't 'NOT OK' but still change the status to OK for ID2 and ID3. How can the code be fixed? Note I'm not allowed to use Create a table (even temporary ones) due to privilege-restrictions.

I could make two SQL calls; first to select by ID where status = not OK, then secondly do this update statement without the "WHERE table1.status= 'not OK'" part, but I'm trying to avoid doing that if possible

This is a bit long for a comment.

Your code does exactly what you specify you want: updating rows that meet both the condition on status and on id s. Here is a db<>fiddle that illustrates this. This fiddle happens to use Postgres, but that really doesn't matter. The code would work the same in any database.

My suspicion is that you have a bug in passing the id s the statuses are just a confusion. You haven't provided enough information to determine where the bug lies. But your SQL code is doing what you want.

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