#1005-无法创建表Musicplayer`.Albums(错误号:150“外键约束格式不正确”)

时间:2019-12-21 13:59:55

标签: mysql sql ddl

我有此代码:

CREATE TABLE Artists 
(
    id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
    name VARCHAR(255) NOT NULL,
    description VARCHAR(255)
);

CREATE TABLE Albums 
(
    id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
    name VARCHAR(255) NOT NULL,
    releasedate DATE,
    artistid INT,
    genreid INT,
    picture VARCHAR(255),

    CONSTRAINT `fk_albums_artists` 
        FOREIGN KEY (artistid) REFERENCES Artists(id),
    CONSTRAINT `fk_albums_genres` 
        FOREIGN KEY (genreid) REFERENCES Genres(id)
);

CREATE TABLE Tracks
(
    id INT(11) AUTO_INCREMENT PRIMARY KEY NOT NULL,
    name VARCHAR(255) NOT NULL,
    playtime INT NOT NULL,
    albumid INT,

    CONSTRAINT `fk_tracks_album` 
        FOREIGN KEY (albumid) REFERENCES Albums(id)    
);

CREATE table Genres
(
    id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
    name VARCHAR(255) NOT NULL
);

我的SQL查询错误:

  

MySQL说:文档

     

1005-无法创建表musicplayerAlbums(错误号:150“外键约束格式不正确”)(详细信息...)

我想了解为什么会出现此错误以及如何解决该错误?

1 个答案:

答案 0 :(得分:2)

依次声明表,以便在引用表之前 定义表。

CREATE TABLE Artists (
    id int AUTO_INCREMENT PRIMARY KEY NOT null,
    name varchar(255) not null,
    description varchar(255)
);

CREATE table Genres(
    id int AUTO_INCREMENT PRIMARY KEY NOT null,
    name varchar(255) not null
);


CREATE TABLE Albums (
    id int AUTO_INCREMENT PRIMARY KEY NOT null,
    name varchar(255) not null,
    releasedate date,
    artistid int,
    genreid int,
    picture varchar(255),
    CONSTRAINT `fk_albums_artists` FOREIGN KEY (artistid) REFERENCES Artists(id),
    CONSTRAINT `fk_albums_genres` FOREIGN KEY (genreid) REFERENCES Genres(id)
);


CREATE TABLE Tracks(
    id int(11) AUTO_INCREMENT PRIMARY KEY NOT null,
    name varchar(255) not null,
    playtime int not null,
    albumid int,
    CONSTRAINT `fk_tracks_album` FOREIGN KEY (albumid) REFERENCES Albums(id)    
);

Here是db <>小提琴。

您仍然可以使用相互引用的表。但是,您将需要使用ALTER TABLE而不是在CREATE TABLE语句中声明此类外键约束。但是,对于这些表定义,您不需要这样做。