在不知道ID的情况下进行更新

时间:2016-05-30 09:14:53

标签: sql sql-server

我有这个要求:

UPDATE PEOPLE SET ID_STATE = 5 WHERE ID_STATE IN (3,4);

我会提出相同的请求,但如果我不知道ID_STATE而只知道labelStatePeople

SELECT ID_STATE FROM STATE_PEOPLE WHERE labelStatePeople = 'blue';

实施例

$1 = SELECT ID_STATE FROM STATE_PEOPLE WHERE labelStatePeople = 'blue';
$2 = SELECT ID_STATE FROM STATE_PEOPLE WHERE labelStatePeople = 'yellow';
$3 = SELECT ID_STATE FROM STATE_PEOPLE WHERE labelStatePeople = 'red';

最终请求: UPDATE PEOPLE SET ID_STATE = $1 WHERE ID_STATE IN ($2,$3);

2 个答案:

答案 0 :(得分:4)

只需要一个子查询即可返回那些奇怪的人的ID_STATE值:

UPDATE PEOPLE
  SET ID_STATE = 5
WHERE ID_STATE IN (SELECT ID_STATE FROM STATE_PEOPLE
                   WHERE labelStatePeople = 'strange'
                    and ID_STATE IS NOT NULL)

(如果该列为ID_STATE IS NOT NULL,则可以删除子查询的NOT NULL部分。)

答案 1 :(得分:1)

试试这个

UPDATE PEOPLE
SET ID_STATE = 5
WHERE ID_STATE 
IN (SELECT ID_STATE FROM STATE_PEOPLE
WHERE labelStatePeople 
IN ('blue','yellow','red') 
AND ID_STATE IS NOT NULL );