我正在尝试运行以下脚本,但它抱怨外键约束问题:
DROP DATABASE IF EXISTS music;
CREATE DATABASE music;
USE music;
CREATE TABLE artist (
artist_id SMALLINT(5) NOT NULL DEFAULT 0,
artist_name CHAR(128) DEFAULT NULL,
PRIMARY KEY (artist_id)
);
CREATE TABLE album (
artist_id SMALLINT(5) NOT NULL DEFAULT 0,
album_id SMALLINT(4) NOT NULL DEFAULT 0,
album_name CHAR(128) DEFAULT NULL,
PRIMARY KEY (artist_id,album_id),
FOREIGN KEY (artist_id) REFERENCES artist(artist_id)
);
CREATE TABLE track (
track_id SMALLINT(3) NOT NULL DEFAULT 0,
track_name CHAR(128) DEFAULT NULL,
artist_id SMALLINT(5) NOT NULL DEFAULT 0,
album_id SMALLINT(4) NOT NULL DEFAULT 0,
time DECIMAL(5,2) DEFAULT NULL,
PRIMARY KEY (artist_id,album_id,track_id),
FOREIGN KEY (album_id) REFERENCES album(album_id),
FOREIGN KEY (artist_id) REFERENCES artist(artist_id)
);
问题似乎是由于artist_id
表中的track
外键引起的,但是我没有看到任何问题。这是完整的错误消息:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2019-10-20 13:04:42 0x1d08 Error in foreign key constraint of table music/track:
FOREIGN KEY (album_id) REFERENCES album(album_id),
FOREIGN KEY (artist_id) REFERENCES artist(artist_id)
):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
Please refer to http://dev.mysql.com/doc/refman/5.7/en/innodb-foreign-key-constraints.html for correct foreign key definition.
------------
答案 0 :(得分:2)
将创建表更改为
CREATE TABLE artist (
artist_id SMALLINT(5) NOT NULL DEFAULT 0,
artist_name CHAR(128) DEFAULT NULL,
PRIMARY KEY (artist_id),
INDEX (artist_id)
);
CREATE TABLE album (
artist_id SMALLINT(5) NOT NULL DEFAULT 0,
album_id SMALLINT(4) NOT NULL DEFAULT 0,
album_name CHAR(128) DEFAULT NULL,
PRIMARY KEY (artist_id,album_id),
INDEX (album_id),
FOREIGN KEY (artist_id) REFERENCES artist(artist_id)
);
错误消息说明了很多。