문제

MySQL에 대한 삽입 쿼리에서 사용자 정의 변수를 사용해야합니다. 벨로우즈 예제를 참조하십시오.

INSERT INTO `posts`(`id`) VALUES(NULL);
SET @last_insert_id = LAST_INSERT_ID();
INSERT INTO `comments`(`id`, `post_id`) VALUES(NULL, "@last_insert_id");
.

이 예제는 작동하지 않고 삽입되지 않습니다. 내가 무엇을 잘못하고 있습니까?

도움이 되었습니까?

해결책

변수에 저장할 필요가 없습니다.다음 LAST_INSERT_ID() 문에서 INSERT를 호출 할 수 있습니다.

INSERT INTO `comments`(`id`, `post_id`) VALUES (NULL, LAST_INSERT_ID());
.

... 해당 ID를 사용하여 수행 할 삽입이 여러 개 있지 않으면

이 경우 변수를 사용하기위한 적절한 구문은 따옴표없이 수행하는 것입니다.

INSERT INTO `posts`(`id`) VALUES (NULL);
SET @last_insert_id = LAST_INSERT_ID();
/* Several new entries using the same @last_insert_id */
INSERT INTO `comments`(`id`, `post_id`) VALUES (NULL, @last_insert_id);
INSERT INTO `comments`(`id`, `post_id`) VALUES (NULL, @last_insert_id);
INSERT INTO `comments`(`id`, `post_id`) VALUES (NULL, @last_insert_id);
INSERT INTO `comments`(`id`, `post_id`) VALUES (NULL, @last_insert_id);
INSERT INTO `comments`(`id`, `post_id`) VALUES (NULL, @last_insert_id);
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top