In a Postgresql database we have a table like below:
=# SELECT * FROM toy_cars;
serial_no | name
------------+---------------
199ER276FN | Snow Doctor
8BE0F79A3R | Flatbed Truck
D76185CE8G | Sand Speeder
=# SELECT * FROM toy_trains;
serial_no | name
-----------------+-------------
BMXH5R4T8K7KELD | Howler T140
B1Q1JJDQW9LQN0G | Quakester
8HO9240TO6RNNQ9 | Medusa 90
=# SELECT * FROM items_for_sale;
serial_no | in_stock
-----------------+---------------
199ER276FN | t
BMXH5R4T8K7KELD | t
B1Q1JJDQW9LQN0G | f
8BE0F79A3R | f
8HO9240TO6RNNQ9 | t
D76185CE8G | f
Note:
Every
serial_nocolumn is the primary key of that table andin_stockis a boolean.serial_noin thetoy_carstable has a regexCHECKrestraint to allow 10 characters only.serial_noin thetoy_trainstable has a regexCHECKrestraint to allow 15 characters only.serial_noin theitems_for_saletable is the serial of either the toy cars or trains, and has a regexCHECKrestraint to allow 10 or 15 characters only.All
serial_nocolumns have theUNIQUErestraint.
We want to add a REFERENCES check to serial_no in the items_for_sale table to make sure that the entered serial is either present in the toy_cars table OR the toy_trains table.
So, if I were to try INSERT INTO items_for_sale VALUES('KYVGK0DBYXPMWW8','f'); this would fail because that serial is not present in either toy_cars or toy_trains.
How can this be done? We prefer to use one table (like it's structured now).