对使用select选择的每个id在sql中运行insert

lnvxswe2  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(223)

这个问题在这里已经有答案了

从select插入sql(3个答案)
两年前关门了。
我有一个选择列(id)并有多行的查询。

SELECT DISTINCT users.ID FROM `users` LEFT JOIN `posts` AS ships ON users.ID = ships.post_author WHERE ships.post_author IS NULL

现在我想为每个id插入posts表,并使用post\u author列中的id

INSERT INTO `posts` (`ID`, `post_author`, `post_date`, `post_date_gmt`) VALUES (NULL, 'THE IDs from the select statement', DATE_SUB(NOW(), INTERVAL 7 HOUR), NOW())

//编辑我想多做点什么,我怎么能再插入一张表呢?作为'post\u id',我需要insert语句中的自动增量id。我认为最后一个插入id()不起作用。

INSERT INTO `postmeta` (`post_id`, `meta_key`, `meta_value`)
VALUES ('ID OF THE ABOVE INSERT', '_start_date', DATE_SUB(NOW(), INTERVAL 7 HOUR));
06odsfpq

06odsfpq1#

你可以这样做:

INSERT INTO `posts` (`ID`, `post_author`, `post_date`, `post_date_gmt`)
SELECT DISTINCT  NULL AS `ID`,
users.ID AS `post_author`,
NOW() - INTERVAL 7 HOUR AS `post_date`,
NOW() AS `post_date_gmt`
FROM `users`
LEFT JOIN `posts` AS ships ON users.ID = ships.post_author
WHERE ships.post_author IS NULL
lp0sw83n

lp0sw83n2#

您可以使用insert-select执行单个查询

INSERT INTO `posts` (`ID`, `post_author`, `post_date`, `post_date_gmt`) 

SELECT DISTINCT  null, users.ID , DATE_SUB(NOW(), INTERVAL 7 HOUR), NOW()
FROM `users` 
LEFT JOIN `posts` AS ships ON users.ID = ships.post_author 
WHERE ships.post_author IS NULL

相关问题