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_no
column is the primary key of that table andin_stock
is a boolean.serial_no
in thetoy_cars
table has a regexCHECK
restraint to allow 10 characters only.serial_no
in thetoy_trains
table has a regexCHECK
restraint to allow 15 characters only.serial_no
in theitems_for_sale
table is the serial of either the toy cars or trains, and has a regexCHECK
restraint to allow 10 or 15 characters only.All
serial_no
columns have theUNIQUE
restraint.
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).