Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MySQL: SELECT from 2 tables, keeping the records of the second table when primary key matches

I have 2 tables with the same structure but different content:

table_a:
+----+------------+
| id | date       |
+----+------------+
|  1 | 2023-02-02 |
|  2 | 2023-10-12 |
|  3 | 2023-02-04 |
+----+------------+

table_b:
+----+------------+
| id | date       |
+----+------------+
|  3 | 2022-11-11 |
+----+------------+

I’m trying to make a query that selects records from both tables, and on duplicate key (in this case 3), select the table_b one.

So the result would be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

query:
+----+------------+
| id | date       |
+----+------------+
|  1 | 2023-02-02 |
|  2 | 2023-10-12 |
|  3 | 2022-11-11 |
+----+------------+

I tried

SELECT * from table_a a left join table_b b on a.id = b.id;
+----+------------+------+------------+
| id | date       | id   | date       |
+----+------------+------+------------+
|  1 | 2023-02-02 | NULL | NULL       |
|  2 | 2023-10-12 | NULL | NULL       |
|  3 | 2023-02-04 |    3 | 2023-11-11 |
+----+------------+------+------------+

Is there a way to overwrite the table_a record with the table_b one to get everything in 2 columns instead of 4?

>Solution :

This can be achieved by simply applying UNION between all records from table_a that do not have a matching id in table_b. Something like:

SELECT *
FROM table_a
WHERE id NOT IN (SELECT id FROM table_b)

UNION

SELECT *
FROM table_b

CODE DEMO

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading