Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
763 views
in Technique[技术] by (71.8m points)

mysql - How can I add a foreign key when creating a new table?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...