I have a mySQL table with a reference set of data in it. I have another table with data in it that describes updates or additional entries to this reference data. For various reasons I won’t get into, it’s important that the reference data stay unaltered as specific users come along and create records (hence the second table). The schema between these tables is identical with the exception of the “custom” table having a 2-key composite primary key. One of those columns is shared between the “custom” and reference tables.
The business logic I want to execute in a single SQL statement on these tables is as follows:
If records exist in the “custom” table with the same key value as what’s in the reference table, then take the “custom”. Otherwise, take the reference value.
I thought maybe I could use a RIGHT JOIN, or perhaps even some twist on the UNION operator to control what was coming back. I keep scrambling up the logic of the SQL though. The JOIN is going to fetch info from one table to join with the other, which I’m really not looking for. The UNION will simply remove duplicates between tables….which is close.
Something like:
SELECT * FROM custom UNION SELECT * FROM reference
Except this will simply drop duplicates if all columns are the same. If any is different (which there will be since that’s why the custom entry exists), then the UNION does nothing but munge both tables’ contents together.
Am I going about this all wrong?
Thanks for any insights you can provide.
There are a few ways to do this. Here is a union that should get what you need, at least according to my interpretation of your situation:
I’m assuming your RefTable and CustomTable have a one-to-zero-or-one relationship, as in, you don’t have multiple Custom records for any Ref (but this will still work either way).
Update:
You might also want your extra key column from Custom: