如何使用外键为新表how to use foreign key into new table

- 此内容更新于:2014-12-30
主题:

我有一个表 创建表的客人(int id(15)not null auto_increment主键,GuestName char(25)not null); 创建表付款(int id(15)not null auto_increment国外关键(id)引用客人(id),BillNr int(15)not null); 第二个命令是什么问题,为什么它不工作请纠正我。它没有创建新表。 谢谢

原文:

I have one 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 Foriegn Key(id) references GUEST(id), BillNr int(15) not null);

what is problem in second command, why it is not working please correct me. it did not create new table. thanks

解决方案:
你问题的答案几乎是一样的答案。 您需要指定包含外键表中包含主键的表的名称,和主键字段的名称(使用“引用”)。 这有一些代码显示如何创建外键,并在创建表。 这里有一个简单的例子从:
原文:

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:

CREATE TABLE parent (id INT NOT NULL,
                 PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
                    INDEX par_ind (parent_id),
                    FOREIGN KEY (parent_id) REFERENCES parent(id)
                      ON DELETE CASCADE
) ENGINE=INNODB;
解决方案:
您可能想要取代国外外国首先,)
原文:

You might want to replace Foriegn by Foreign for starters ;)

解决方案:
我将建议一个唯一键的付款表。在它的身边,外键不应该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.

CREATE TABLE GUEST(id int(15) not null auto_increment PRIMARY KEY, GuestName char(25) not null)  ENGINE=INNODB;

CREATE TABLE PAYMENT(id int(15)not null auto_increment, Guest_id int(15) not null, INDEX G_id (Guest_id), Foreign Key(Guest_id) references GUEST(id), BillNr int(15) not null)  ENGINE=INNODB;
解决方案:
确保你使用InnoDB引擎数据库,或两个表。从MySQL参考: 除了InnoDB存储引擎, MySQL服务器解析的外键 在CREATE TABLE语句的语法,但是 不使用或储存。
原文:

Make sure you're using the InnoDB engine for either the database, or for both tables. From the MySQL Reference:

For storage engines other than InnoDB, MySQL Server parses the FOREIGN KEY syntax in CREATE TABLE statements, but does not use or store it.

解决方案:
int(15)之间应该有空间,而不是null
原文:

There should be space between int(15) and not null