我很难将外键应用于 postgres musicbrainz 数据库。
我使用这些出色的说明让我走到了这一步:
https://bitbucket.org/lalinsky/mbslave
我在 postgres 中加载了所有数据。
我创建了主键和索引。
但是,当我尝试应用外键时,我收到了这个奇怪的错误:
musicbrainz@ip-10-217-5-18:/home/ubuntu/mbslave$ psql < sql/CreateFKConstraints.sql
ERROR: insert or update on table "annotation" violates foreign key constraint "annotation_fk_editor"
DETAIL: Key (editor)=(51298) is not present in table "editor".
SQL 脚本的第一行似乎出错了:
ALTER TABLE annotation
ADD CONSTRAINT annotation_fk_editor
FOREIGN KEY (editor)
REFERENCES editor(id);
我是 postgres 的新手,很难理解这个错误信息。
第一行让我相信外键约束已经创建。但我不认为它有。
musicbrainz=> SELECT
musicbrainz-> tc.constraint_name, tc.table_name, kcu.column_name,
musicbrainz-> ccu.table_name AS foreign_table_name,
musicbrainz-> ccu.column_name AS foreign_column_name
musicbrainz-> FROM
musicbrainz-> information_schema.table_constraints AS tc
musicbrainz-> JOIN information_schema.key_column_usage AS kcu
musicbrainz-> ON tc.constraint_name = kcu.constraint_name
musicbrainz-> JOIN information_schema.constraint_column_usage AS ccu
musicbrainz-> ON ccu.constraint_name = tc.constraint_name
musicbrainz-> WHERE constraint_type = 'FOREIGN KEY' AND tc.table_name='annotation';
constraint_name | table_name | column_name | foreign_table_name | foreign_column_name
-----------------+------------+-------------+--------------------+---------------------
(0 rows)
错误消息中的第二行令人困惑。听起来好像在编辑器表中找不到 id 列。但它就在那里。
musicbrainz=> \d editor
Table "musicbrainz.editor"
Column | Type | Modifiers
---------------------+--------------------------+-----------------------------------------------------
id | integer | not null default nextval('editor_id_seq'::regclass)
name | character varying(64) | not null
privs | integer | default 0
email | character varying(64) | default NULL::character varying
website | character varying(255) | default NULL::character varying
bio | text |
member_since | timestamp with time zone | default now()
email_confirm_date | timestamp with time zone |
last_login_date | timestamp with time zone | default now()
edits_accepted | integer | default 0
edits_rejected | integer | default 0
auto_edits_accepted | integer | default 0
edits_failed | integer | default 0
last_updated | timestamp with time zone | default now()
birth_date | date |
gender | integer |
area | integer |
password | character varying(128) | not null
ha1 | character(32) | not null
deleted | boolean | not null default false
Indexes:
"editor_pkey" PRIMARY KEY, btree (id)
"editor_idx_name" UNIQUE, btree (lower(name::text))
建议?