Radhika Kulkarni
Radhika Kulkarni

Reputation: 488

insert data into table having foreign key

I have two tables linked as follows:

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

and

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)
)

I insert data in property_details table. eg..

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

Now, i want to enter data in hilton table. Can u tell me how should i write query for entering data in hilton table?

Upvotes: 0

Views: 990

Answers (2)

kenda
kenda

Reputation: 488

Just insert as before:

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

See this SQL fiddle: http://sqlfiddle.com/#!9/456ba/1

Probably see also: how to insert foreign key in a table

Upvotes: 0

rbr94
rbr94

Reputation: 2277

You firstly have to insert data in the PrimaryKey Table (property_details), so that there is a PrimaryKey you can reference in the ForeignKey Table (hilton).

1)

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

2)

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

Upvotes: 1

Related Questions