私の意見では、最も洗練された解決策は、継承を使用してサブタイプの動作を取得することです。
継承を使用した PostgreSQL 9.3 スキーマのセットアップ:
create table B ( id int primary key );
-- Instead to create a 'type' field, inherit from B for
-- each type with custom properties:
create table B_X ( -- some_data varchar(10 ),
constraint pk primary key (id)
) inherits (B);
-- Sample data:
insert into B_X (id) values ( 1 );
insert into B (id) values ( 2 );
-- Now, instead to reference B, you should reference B_X:
create table A ( id int primary key, B_id int references B_X(id) );
-- Here it is:
insert into A values ( 1, 1 );
--Inserting wrong values will causes violation:
insert into A values ( 2, 2 );
エラー: テーブル "a" の挿入または更新は、外部キー制約 "a_b_id_fkey" に違反しています 詳細: キー (b_id)=(2) がテーブル "b_x" に存在しません。
ベース テーブル からすべてのデータを取得しています:
select * from B
結果:
| id |
|----|
| 2 |
| 1 |
タイプのデータを取得しています:
SELECT p.relname, c.*
FROM B c inner join pg_class p on c.tableoid = p.oid
結果:
| relname | id |
|---------|----|
| b | 2 |
| b_x | 1 |