I have the following table:
create table sales
(id,transaction_ref,type,amount,je_id)
as values
(1,'a','invoice',100,null)
,(2,'b','invoice',200,null)
,(3,'c','invoice',300,null)
,(4,'d','invoice',400,null)
,(5,'a','entry',10,null)
,(6,'b','entry',20,null)
,(7,'c','entry',30,null)
,(8,'d','entry',40,null);
I want to match the records on the basis of transaction_ref
and then update the ids of entry
type records in invoice
type records in column je_id
.
The result should look like this:
id | transaction_ref | type | amount | je_id |
---|---|---|---|---|
1 | a | invoice | 100 | 5 |
2 | b | invoice | 200 | 6 |
3 | c | invoice | 300 | 7 |
4 | d | invoice | 400 | 8 |
5 | a | entry | 10 | null |
6 | b | entry | 20 | null |
7 | c | entry | 30 | null |
8 | d | entry | 40 | null |
I tried the following but it’s not working: DB<>Fiddle
UPDATE sales SET je_id = id
WHERE type = 'invoice'
AND transaction_ref = transaction_ref;
id | transaction_ref | type | amount | je_id |
---|---|---|---|---|
1 | a | invoice | 100 | 1 |
2 | b | invoice | 200 | 2 |
3 | c | invoice | 300 | 3 |
4 | d | invoice | 400 | 4 |
5 | a | entry | 10 | null |
6 | b | entry | 20 | null |
7 | c | entry | 30 | null |
8 | d | entry | 40 | null |
4
Answers
With join:
Result:
Try:
Typically, you would get the IDs in a sub query:
This is a quite basic update statement and works in about every RDBMS.
As to your own statement: This cannot work.
WHERE transaction_ref = transaction_ref
is true for every row in the table of course, so you update every row.SET je_id = id
updates a row’s je_id with the row’s id. This is not what you want.UPDATE..FROM
results in an implicitJOIN
. Give your target and source records an alias, then specify what needs to join to what.In your case, targets are
type='invoice'
, sourcestype='entry'
:demo at db<>fiddle
Quoting the
UPDATE
doc:Further:
And that’s exactly what you need: repeat the target to get a self-join, give it an alias.