MySql中的外键作为复合主键

时间:2014-05-20 21:04:08

标签: mysql sql foreign-keys composite-primary-key mysql-error-1005

我的数据库名称为Shop with this 3 tables:

    create table usr(
    id_usr varchar(20) not null,
    primary key(id_usr)

);

create table product(
    id_product varchar(20) not null,
    id_size varchar(20) not null,
    price float(4,2) unsigned,
    primary key(id_product,id_size)
);

create table cart(
    myUser varchar(20), 
    mySize varchar(20),
    product varchar(20),
    qty int not null,
    primary key(myUser,product,mySize),
    FOREIGN KEY (myUser) REFERENCES usr (id_usr),
    FOREIGN KEY (product) REFERENCES product (id_product),
    FOREIGN KEY (mySize) REFERENCES product (id_size)
);

当我在sql中编译时,它给了我这条消息:

1005 - 无法创建表格' Shop.cart' (错误:150)

如果我尝试删除外键mySize(FOREIGN KEY(mySize)REFERENCES prodotto(id_size)) 它有效,为什么我有这个消息?

2 个答案:

答案 0 :(得分:3)

您正在对product表格进行FK引用,但只定义了密钥的一部分。尝试...

FOREIGN KEY (product, mySize) REFERENCES product (id_product, id_size),

答案 1 :(得分:1)

我的猜测是你还没有创建你的prodotto表。这有效:

create table user(
    id_user varchar(20) not null,
    primary key(id_user)

);

create table product(
    id_product varchar(20) not null,
    id_size varchar(20) not null,
    price float(4,2) unsigned,
    primary key(id_product,id_size)
);

create table prodotto (
  id_size varchar(20) primary key
);

create table cart(
    myUser varchar(20), 
    mySize varchar(20),
    product varchar(20),
    qty int not null,
    primary key(myUser,product,mySize),
    FOREIGN KEY (myUser) REFERENCES user (id_user),
    FOREIGN KEY (product) REFERENCES product (id_product),
    FOREIGN KEY (mySize) REFERENCES prodotto (id_size)
);