Search Posts

MySQL – Select values and remove duplicates by table name

how to – MySQL – Select values and remove duplicates by table name

I have two tables which have the same structure but another names (in first tables I store default values and in second table I store saved values by user).

I select these values using union all:

SELECT * FROM `table_default` UNION ALL SELECT * FROM `table_saved`

Structure of table_default:

| ID | SOME_VAL |
|  1 | def_val  |
|  2 | def_val  |
|  3 | def_val  |

Structure of table_saved:

| ID | SOME_VAL |
|  1 |   test   |
|  3 |   text   |

And now, when I using this query:

SELECT * FROM `table_default` UNION ALL SELECT * FROM `table_saved`

I got:

| ID | SOME_VAL |
|  1 | def_val  |
|  2 | def_val  |
|  3 | def_val  |
|  1 |   test   |
|  3 |   text   |

But I want to get unique values by ID. Table_saved is more important so when select return duplicates I want to remove always record from table_default.
So finally I want to get:

| ID | SOME_VAL |
|  2 | def_val  | --> from TABLE_DEFAULT because this record (by ID) is not exist in table_saved
|  1 |   test   | --> from TABLE_SAVED
|  3 |   text   | --> from TABLE_SAVED

I can’t use GROUP BY id because I don’t know which record will be remove (sometime GROUP BY remove duplicate from table_default but sometimes GROUP BY also remove duplicates from table_saved) so I can’t manage this.

Is it possible to remove duplicates (something like GROUP BY) using table name and row name ? Or maybe somebody has another idea. Please help.

Thanks.

Source: Stackoverflow

Leave a Reply

Your email address will not be published. Required fields are marked *