I’m re-posting a more clear version of a previous question I deleted.
As the example below shows, I want to combine table_b into table_a only if table_b‘s id doesn’t appear in table_a‘s table_b_id column. Each table should have a null value for any fields it doesn’t have.
Example:
table_a
+----+-------+------------+
| id | name | table_b_id |
+----+-------+------------+
| 0 | mike | 1 |
+----+-------+------------+
| 1 | jack | 1 |
+----+-------+------------+
table_b
+----+-------+
| id | name |
+----+-------+
| 0 | tom |
+----+-------+
| 1 | joe |
+----+-------+
Result:
+-------------+-------+------------+
| original_id | name | table_b_id |
+-------------+-------+------------+
| 0 | mike | 1 |
+-------------+-------+------------+
| 0 | tom | |
+-------------+-------+------------+
| 1 | jack | 1 |
+-------------+-------+------------+
Your question can almost directly be translated into a query. You want to see table A queried but supplemented with rows from B for which
idof B is not in anytable_b_idof A. So the followingUNIONcombines A with the subset of B whereidof B is not intable_b_id:Note that for the second set we select
NULLastable_b_idbecause A does not have this field.