How to automate insert id into child table with new created id from parent
How to make as 开发者_如何学Cdefault insert with id_user into child user_id? I will make at once update without extra select and insert in my program. Is this possible?
CREATE TABLE IF NOT EXISTS `users` (
`id_user` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(25) NOT NULL DEFAULT '',
PRIMARY KEY (`id_user`)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `scores` (
`user_id` INT( 10 ) NOT NULL DEFAULT '0',
`score` INT( 10 ) NOT NULL DEFAULT '0',
PRIMARY KEY (`user_id`),
CONSTRAINT FOREIGN KEY ( `user_id` ) REFERENCES `users` ( `id_user` )
ON UPDATE CASCADE
) ENGINE = INNODB;
INSERT INTO users (name) VALUES ('i am');
UPDATE scores SET score = '10' WHERE user_id = '1';
Not sure I understand the example. If you just inserted user number 1, how come there is a record in scores
with user_id = 1
?.
Anyway, If your question is how to get the id of the user you just inserted into users
so you can insert a child record into scores
, you can run
SELECT LAST_INSERT_ID();
after the first insert, and use the result for the second insert (/update).
精彩评论