创建新表时如何添加外键?
我有这两个 CREATE TABLE
语句:
CREATE TABLE GUEST (
id int(15) not null auto_increment PRIMARY KEY,
GuestName char(25) not null
);
CREATE TABLE PAYMENT (
id int(15) not null auto_increment
Foreign Key(id) references GUEST(id),
BillNr int(15) not null
);
第二个语句有什么问题? 它没有创建新表。
I have these two CREATE TABLE
statements:
CREATE TABLE GUEST (
id int(15) not null auto_increment PRIMARY KEY,
GuestName char(25) not null
);
CREATE TABLE PAYMENT (
id int(15) not null auto_increment
Foreign Key(id) references GUEST(id),
BillNr int(15) not null
);
What is the problem in the second statement? It did not create a new table.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的问题的答案与 这个 的答案几乎相同。
您需要在包含外键的表中指定包含主键的表的名称以及主键字段的名称(使用“引用”)。
这有一些代码展示了如何自己创建外键,并在 CREATE TABLE 中创建。
这是其中一个更简单的示例:
The answer to your question is almost the same as the answer to this one .
You need to specify in the table containing the foreign key the name of the table containing the primary key, and the name of the primary key field (using "references").
This has some code showing how to create foreign keys by themselves, and in CREATE TABLE.
Here's one of the simpler examples from that:
我建议为付款表设置一个唯一的密钥。 另一方面,外键不应该是 auto_increment,因为它引用已经存在的键。
I will suggest having a unique key for the payment table. On it's side, the foreign key should not be auto_increment as it refer to an already existing key.
确保您对数据库或两个表使用 InnoDB 引擎。 来自 MySQL 参考:
Make sure you're using the InnoDB engine for either the database, or for both tables. From the MySQL Reference:
int(15)
和not null
之间应该有空格There should be space between
int(15)
andnot null