vendredi 26 février 2016

SQLite update with join not possible, what do I use?

I have a table as follows:

ID   Col_A    Col_B

1    P-1      123
2    S        123
3    P-3      456
4    S        456

ID is the primary key.

What I want to do is concatenate the ID of rows 1 and 3 to Col_A of rows 2 and 4, based on Col_B equivalence. In other words, where Col_A = 'S', find the ID of the row with the same value in Col_B, and add that ID to Col_A.

The result would be:

1    P-1    123
2    S-1    123
3    P-3    456
4    S-3    456      

Could someone please show me how to write this query in SQLite, I am having no success.

In SQL server I use an inner join on the same table, and this works:

UPDATE A
SET A.Col_A = 'S-' + CAST(B.ID as VARCHAR(24)) 
FROM Table1 A
INNER JOIN Table1 B ON
A.Col_B = B.Col_B 
WHERE A.Col_A = 'S';

As far as I can tell you can't use a join in SQLite within an update, but have no idea what to do instead.

I have tried:

UPDATE Table1
SET Col_A = 'S' || (SELECT B.ID from Table1 B WHERE B.Col_B = Col_B)
WHERE Col_A = 'S';   

This results in:

1    P-1    123
2    S-1    123
3    P-3    456
4    S-1    456 

Aucun commentaire:

Enregistrer un commentaire