How can I select all rows from two SQLite tables, but prefer one if there are matching rows in both?
0
votes
2
answers
155
views
I have two tables, each with a
round
and an id
column and additional data columns. One table is the planned version, the other one is the actual one. E.g.:
planned:
round | id | value
------+----+------
1 | 1 | a
------+----+------
2 | 1 | d
------+----+------
2 | 2 | e
actual:
round | id | value
------+----+------
1 | 1 | a
------+----+------
1 | 2 | b
------+----+------
2 | 1 | c
Now I want to select all data, but if such a dataset (identified by round
and id
) is present both in the planned
and in the actual
table, I want to use the actual
value. Additionally, all planned
values not present in the actual
table should be selected.
In this example, I'd like to get:
round | id | value
------+----+------
1 | 1 | a (present in both, but identical)
------+----+------
1 | 2 | b ("actual" values, not present in "planned")
------+----+------
2 | 1 | c ("actual" values, different from "planned")
------+----+------
2 | 2 | e ("planned" values, not present in "actual")
Edit: I found a way to select this using two UNION
ed queries, one with a subquery:
SELECT round, id, value FROM actual
UNION
SELECT round, id, value FROM planned
WHERE NOT EXISTS (
SELECT TRUE FROM actual
WHERE actual.round = planned.round
AND actual.id = planned.id
)
ORDER BY round, id
but this seems to be a bit clumsy … is there a more elegant way?
Asked by Tobias Leupold
(137 rep)
Jul 24, 2024, 04:03 PM
Last activity: Jul 24, 2024, 06:31 PM
Last activity: Jul 24, 2024, 06:31 PM