声明两个也是主键的外键

时间:2015-02-25 09:50:03

标签: mysql foreign-keys innodb

我通过在表上声明两个外键来面对一个奇怪的问题,这也是我表中的主键。这是我的sql代码:

CREATE TABLE IF NOT EXISTS guest (
    id_guest varchar(50) NOT NULL,
    PRIMARY KEY(id_guest)
) ENGINE=InnoDb DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS product (
    id_product varchar(100) NOT NULL,
    PRIMARY KEY(id_product)
) ENGINE=InnoDb DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS product_guest_resale (
    id_guest varchar(50) NOT NULL,
    id_product varchar(100) NOT NULL,
    amount int(100) NOT NULL, 
    PRIMARY KEY (id_guest, id_product),
    FOREIGN KEY id_guest REFERENCES guest(id_guest),
    FOREIGN KEY id_product REFERENCES product(id_product)
) ENGINE=InnoDb DEFAULT CHARSET=latin1;

当我执行我的代码时,我得到了这个错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'REFERENCES guest(id_guest),
FOREIGN KEY id_product REFERENCES product(' at line 6

出了什么问题?

1 个答案:

答案 0 :(得分:1)

你错过了括号:

CREATE TABLE IF NOT EXISTS product_guest_resale (
    id_guest varchar(50) NOT NULL,
    id_product varchar(100) NOT NULL,
    amount int(100) NOT NULL, 
    PRIMARY KEY (id_guest, id_product),
    FOREIGN KEY (id_guest) REFERENCES guest(id_guest),
    FOREIGN KEY (id_product) REFERENCES product(id_product)
) ENGINE=InnoDb DEFAULT CHARSET=latin1;