将数据插入具有外键的表中

时间:2016-09-21 11:04:43

标签: mysql foreign-keys

我有两个表链接如下:

CREATE TABLE `property_details`(
    id INT NOT NULL,
    `name` VARCHAR(100),
    PRIMARY KEY(id)
)

CREATE TABLE `hilton`(
`property_id` INT NOT NULL,
`start_date` DATE DEFAULT NULL,
`end_date` DATE DEFAULT NULL,
`msg` VARCHAR(100) DEFAULT NULL, 
`sunday` INT(11),
`monday` INT(11),
`tuesday` INT(11),
`wednesday` INT(11),
`thursday` INT(11),
`friday` INT(11),
`saturday` INT(11),
FOREIGN KEY(property_id) REFERENCES property_details(id)
)

我在property_details表中插入数据。例如..

INSERT INTO property_details(`id`,`name`) VALUES ('1','Hilton');

现在,我想在hilton表格中输入数据。你能告诉我如何编写查询以在hilton表中输入数据吗?

2 个答案:

答案 0 :(得分:1)

您首先必须在PrimaryKey表(property_details)中插入数据,以便在PrimaryKey表(ForeignKey)中引用hilton

1)

INSERT INTO property_details('id','name') VALUES ('1','Hilton');

2)

INSERT INTO hilton ('property_id',...) VALUES ('1',...);

答案 1 :(得分:0)

只需像以前一样插入:

INSERT INTO hilton(`property_id`, `sunday`, `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`)
VALUES (1, 0, 1, 2, 3, 4, 5, 6);

请参阅此SQL小提琴:http://sqlfiddle.com/#!9/456ba/1

也可以看到:how to insert foreign key in a table