nandeesh
nandeesh

Reputation: 24820

Update a column after joining two tables with where clause

I have two tables

threads table

_id   recipient_id    type
 1     1
 2     1
 3     2

and addresses table

_id    address
1      HELLO
2      BYE 

recipient_id is mapped to addresses table's _id

I need to update type to a specific value if address is HELLO. How do i do it? I have already tried

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

But i am getting an error near ".": syntax error . What is the correct syntax to update a column?

Upvotes: 1

Views: 357

Answers (1)

user647772
user647772

Reputation:

You can use the IN operator:

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;

Upvotes: 2

Related Questions