I need to collect data from different tables, without duplicates and with a column that collects the presence where I've found each item. So, this is my scenario:
TABLEA
| itemId | name |
|---|---|
| 1 | John |
| 2 | Sam |
TABLEB
| itemId | name |
|---|---|
| 1 | John |
| 3 | Thomas |
I need a view with this result:
| itemId | source_tables |
|---|---|
| 1 | TABLEA,TABLEB |
| 2 | TABLEA |
| 3 | TABLEB |
TRY 1 with this simple UNION query
SELECT TABLEA.itemId AS itemId, 'TABLEA' AS source_tables FROM TABLEA
UNION
SELECT TABLEB.itemId AS itemId, 'TABLEB' AS source_tables FROM TABLEB
I get this result:
itemId source_tables 1 TABLEA 2 TABLEA 1 TABLEB 3 TABLEB
but itemId obviously are duplicated.
TRY 2 with this query
SELECT itemId, group_concat(source_table separator ';') AS source_tables FROM ( SELECT itemId, 'TABLEA' AS source_table FROM TABLEA
UNION ALL
SELECT itemId, 'TABLEB' AS source_table FROM TABLEB ) T1 GROUP BY itemId
I get the expected result. Does anybody knows a better way? is it the best approach?