我想借助其他表的外键更新一个表。
我正在尝试做这样的事情:
UPDATE tbl_1
SET field1 = 6, field12 = NULL
WHERE field3 = (SELECT tbl_2.item1
FROM tbl_1, tbl_2
WHERE tbl_1.field3 = tbl_2.item1 AND tbl_2.item2 = 135)
OR
UPDATE tbl_1
SET field1 = 6, field12 = NULL
WHERE field3 = (SELECT item1 FROM tbl_2 WHERE item2 = 135)
答案 0 :(得分:7)
我认为以下任何一种都可行:
UPDATE tbl_1
SET field1 = 6, field12 = NULL
WHERE EXISTS
( SELECT 1
FROM tbl_2
WHERE tbl_1.field3 = tbl_2.item1
AND tbl_2.item2 = 135
)
或强>
UPDATE tbl_1
SET field1 = 6, field12 = NULL
WHERE field3 IN (SELECT item1 FROM tbl_2 WHERE item2 = 135)
答案 1 :(得分:4)
这是因为SELECT返回多行。这样做:
UPDATE tbl_1 SET field1 = 6, field12 = NULL
WHERE field3 IN (SELECT item1 FROM tbl_2 WHERE item2 = 135)
当SELECT
返回一个表(或多行)时,使用IN
。如果您确定内部查询应该只返回一行,那么您必须相应地调整内部查询。像这样左右:
UPDATE tbl_1 SET field1 = 6, field12 = NULL
WHERE field3 = (SELECT item1 FROM tbl_2 WHERE item2 = 135 ORDER BY myValue LIMIT 1)
在这里使用IN
更安全'因为它可以处理从SELECT语句返回的单个记录和多个记录。
答案 2 :(得分:3)
您还可以使用INSERT OR REPLACE语句,如下所示:
假设tbl_1有4列:key,field1,field2,field3
并且您希望使用tbl_2
INSERT OR REPLACE INTO tbl_1
SELECT tbl_1.key, tbl_1.field1, tbl_2.value, tbl_1.field3
FROM tbl_1 JOIN tbl_2 ON tbl_2.key = tbl_1.key
答案 3 :(得分:0)
单值:
UPDATE tbl_1
SET field1 = 6, field12 = NULL
WHERE field3 = (SELECT tbl_2.item1
FROM tbl_1, tbl_2
WHERE tbl_1.field3 = tbl_2.item1 AND tbl_2.item2 = 135)
对于多个值
UPDATE tbl_1
SET field1 = 6, field12 = NULL
WHERE field3 IN (SELECT tbl_2.item1
FROM tbl_1, tbl_2
WHERE tbl_1.field3 = tbl_2.item1 AND tbl_2.item2 = 135)
答案 4 :(得分:0)
你可以像这样使用
UPDATE tbl_1
SET field1 = 6, field12 = NULL
WHERE field3 in (SELECT tbl_2.item1
FROM tbl_1, tbl_2
WHERE tbl_1.field3 = tbl_2.item1 AND tbl_2.item2 = 135)
sqlite不支持加入更新查询。所以这是选项之一