Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...