I have two tables that are almost identical, representing data from the server, and user-entered data. I would like to display a list to the user of the combined data from the two, merging any duplicates of the value of one text column. When a row is selected, I then need to be able to access data from child tables, so will need the primary key and which table the key is from.
Both tables have unique constraints on (fk_id, column_a).
Server Table:
_id | fk_id | column_a
----------------------
1 | 1 | val 1
2 | 1 | val 2
3 | 2 | val 3
User-Entered Table:
_id | uuid | fk_id | column_a
-----------------------------
1 | xxxx | 1 | val 1
2 | xxxx | 1 | val 4
3 | xxxx | 2 | val 5
The search results I need would then be:
_id | server_id | user_id | fk_id | column_a
--------------------------------------------
1 | 1 | 1 | 1 | val 1
2 | 2 | | 1 | val 2
3 | 3 | | 2 | val 3
2 | | 2 | 1 | val 4
3 | | 3 | 2 | val 5
I do not actually care what is in the _id column of the result set, but I need _id, as I am using a CursorAdaptor in Android.
I was hoping to do this using a view like this:
CREATE VIEW `all_values` AS
SELECT
_id, _id AS 'server_id', fk_id, column_a
FROM
server_table
UNION SELECT
_id, _id AS 'user_id', fk_id, column_a
FROM
user_table
ORDER BY column_a;
Which I could query like this:
SELECT * FROM all_values WHERE fk_id = ?
Is this possible to do using a UNION? A UNION will not contain duplicates, and a UNION ALL will contain all values. Is there a way to merge duplicates, or will I need to do a join based on the value of column_a?
Aucun commentaire:
Enregistrer un commentaire