使用where子句连接两个表后更新列

时间:2012-10-11 06:58:38

标签: database sqlite

我有两张桌子

线程表

_id   recipient_id    type
 1     1
 2     1
 3     2

和地址表

_id    address
1      HELLO
2      BYE 

recipient_id映射到地址表的_id

如果地址为HELLO,我需要将type更新为特定值。我该怎么做?我已经尝试了

UPDATE   threads SET threads.type = 106 FROM threads  
   INNER JOIN 
   addresses  ON addresses._id = threads.recipient_ids
    AND
   addresses.address LIKE '%HELLO%';

但我收到错误near ".": syntax error。 更新列的正确语法是什么?

1 个答案:

答案 0 :(得分:2)

您可以使用IN运算符:

sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE threads (_id integer primary key, recipient_id integer, type text);
INSERT INTO "threads" VALUES(1,1,NULL);
INSERT INTO "threads" VALUES(2,1,NULL);
INSERT INTO "threads" VALUES(3,2,NULL);
CREATE TABLE addresses (_id integer primary key, address text);
INSERT INTO "addresses" VALUES(1,'HELLO');
INSERT INTO "addresses" VALUES(2,'BYE');
COMMIT;
sqlite> update threads set type = 106 where _id in
   ...> (select t._id from threads t, addresses  a
   ...>  where t.recipient_id = a._id and a.address like '%HELLO%');
sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE threads (_id integer primary key, recipient_id integer, type text);
INSERT INTO "threads" VALUES(1,1,'106');
INSERT INTO "threads" VALUES(2,1,'106');
INSERT INTO "threads" VALUES(3,2,NULL);
CREATE TABLE addresses (_id integer primary key, address text);
INSERT INTO "addresses" VALUES(1,'HELLO');
INSERT INTO "addresses" VALUES(2,'BYE');
COMMIT;