从select语句更新所有条目的表

时间:2013-11-23 15:30:14

标签: sql sqlite

在我的场景中,我从条件为true的表中选择所有条目,将其放入向量并通过循环使用update语句,传递向量的值。它有效。

SELECT * FROM MAP AS A WHERE EXISTS  
(SELECT (X, Y) FROM MAP AS B WHERE B.X = A.X + 1 AND B.Y = A.Y ) AND EXISTS     
(SELECT (X, Y) FROM MAP AS C WHERE C.X = A.X - 1 AND C.Y = A.Y ) ;

for...
UPDATE MAP SET VAL = 2 WHERE X = ? AND Y = ?; 
...

但是我想尝试使用单个语句来完成这个目标,而我们可以使用select语句更新表,在我的场景中,在选择记录之前需要检查2个键,所以我不是能够将x或y的where条件放在一起。

UPDATE MAP SET USED = 1 WHERE EXISTS (
SELECT * FROM MAP AS A WHERE EXISTS  
(SELECT (X, Y) FROM MAP AS B WHERE B.X = A.X + 1 AND B.Y = A.Y ) AND EXISTS     
(SELECT (X, Y) FROM MAP AS C WHERE C.X = A.X - 1 AND C.Y = A.Y ) );

当我将上述存在条件置于其中时,它会更新所有条目。如何在一个查询中更新表?

2 个答案:

答案 0 :(得分:1)

子查询的问题在于它没有引用UPDATE语句中的表(MAP)。

只需删除MAP AS A子查询并直接引用MAPUPDATE不允许使用表别名):

UPDATE MAP
SET USED = 1
WHERE EXISTS (SELECT 1 FROM MAP AS B WHERE B.X = MAP.X + 1 AND B.Y = MAP.Y)
  AND EXISTS (SELECT 1 FROM MAP AS C WHERE C.X = MAP.X - 1 AND C.Y = MAP.Y)

答案 1 :(得分:-1)

由于您已验证子查询是否返回您要更新的行,因此您的更新应如下所示:

UPDATE MAP SET USED = 1 
WHERE (X,Y) IN (
SELECT X, Y FROM MAP AS A WHERE EXISTS  
(SELECT X, Y FROM MAP AS B WHERE B.X = A.X + 1 AND B.Y = A.Y ) AND EXISTS     
(SELECT X, Y FROM MAP AS C WHERE C.X = A.X - 1 AND C.Y = A.Y ) );