今日、MySql データベースを PostgreSQL に移植し始めましたが、外部キーとその「共有」に問題があります。
それを説明する方法がわからないので、作成スクリプトの疑似コードを次に示します。
create table id_generator (
id serial PRIMARY KEY,
description varchar(50) );
create table parent (
id REFERENCES id_generator(id),
--content );
create table child (
id REFERENCES id_generator(id),
id_parent REFERENCES parent(id),
--content );
したがって、1 つのテーブルを「id_generator」として使用して ID を作成し、他のテーブルに値テーブルへの参照を与えます。MySql では問題がなかったので、PostgreSQL でも動作するようにしたいと考えています。
そのスクリプトを実行すると、参照を作成するにはテーブルにprimary key
/が必要であるというエラーが表示されます。だから私はそれを次のように変更しました:unique
parent
create table id_generator (
id serial PRIMARY KEY,
description varchar(50) );
create table parent (
id REFERENCES id_generator(id) PRIMARY KEY,
--content );
create table child (
id REFERENCES id_generator(id),
id_parent REFERENCES parent(id),
--content );
したがって、サーバーは作成スクリプトを受け入れ、すべてがいくつかの挿入用に設定されます。
最初の ID を次のように作成します。
insert into id_generator(description) values("parentID");
次に、親を追加します。
insert into parent(id, /*content*/) values(1, /*content*/);
これも期待どおりに機能するため、child
forを挿入する必要がありparent
ます。
insert into id_generator(description) values("childID");
insert into child(id,id_parent)values(2,1);
ここで、「エラー: 重複したキー値が一意の制約に違反しています。詳細: キー (id_parent)=(1) は既に存在します」というエラー メッセージが表示されます。
編集:
\d child;
Tabelle ╗public.child½
Spalte | Typ | Attribute
-------------------+---------+-----------
id | integer | not null
id_parent | integer |
Indexe:
"child_pkey" PRIMARY KEY, btree (id)Fremdschlⁿssel-Constraints:
"child_id_parent_fkey" FOREIGN KEY (id_parent) REFERENCES parent(id)
"child_id_generator_fkey" FOREIGN KEY (id) REFERENCES id_generator(id)
どうすればそれを解決できますか?