[英]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.我正在尝试创建一个 SQL 语句,该语句将表的“状态”列中的特定行从“不正常”更新为“正常”,但仅适用于具有提供的 ID 和状态的行。
Data in table (table1.id, table1.status) = [ID1, PENDING], [ID2, NOT OK], [ID3, NOT OK]表中的数据 (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.一个 ID 列表将从 java 传递到“in ()”部分,我只有 ID,没有状态数据。 Notice that ID1's status that is not 'NOT OK'.
请注意,ID1 的状态不是“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.如果括号内的列表包含所有带有“NOT OK”的 ID,它将对括号中的所有 ID 进行更改。 But if one of the ID contains a different status, it won't make any changes.
但如果其中一个 ID 包含不同的状态,则不会进行任何更改。
The statement should ignore ID1 because its status isn't 'NOT OK' but still change the status to OK for ID2 and ID3.该语句应忽略 ID1,因为它的状态不是“不正常”,但仍将 ID2 和 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;我可以打两个 SQL 电话; 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
首先通过 ID 到 select where status = not OK,然后在没有“WHERE table1.status = 'not OK'”部分的情况下执行此更新语句,但我尽量避免这样做
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.您的代码完全按照您指定的方式执行:更新同时满足
status
和id
条件的行。 Here is a db<>fiddle that illustrates this. 这是一个说明这一点的 db<>fiddle。 This fiddle happens to use Postgres, but that really doesn't matter.
这个小提琴恰好使用 Postgres,但这并不重要。 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.我的怀疑是你在传递
id
时有一个错误,状态只是一个混乱。 You haven't provided enough information to determine where the bug lies.您没有提供足够的信息来确定错误所在。 But your SQL code is doing what you want.
但是您的 SQL 代码正在做您想做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.