[英]MySQL insert record to one table to another if postid is not exist
Is there any way to write query in better way than this if I want to insert postid
from posts
table to star_ratings
table if the postid
is not exists in star_ratings
table. 有没有什么办法来写查询在比这更好的方式,如果我想插入
postid
从posts
表star_ratings
表,如果该postid
不存在于star_ratings
表。
INSERT INTO star_ratings(post_id)
SELECT postid FROM posts
WHERE type in ('D', 'B')
AND postid NOT IN (SELECT post_id FROM star_ratings)
ORDER BY postid ASC
The following EXISTS
query might perform slightly better than what you have: 以下
EXISTS
查询的性能可能比您拥有的更好:
INSERT INTO star_ratings (post_id)
SELECT p.postid
FROM posts p
WHERE
p.type IN ('D', 'B') AND
NOT EXSITS (SELECT 1 FROM star_ratings s WHERE p.post_id = s.post_id);
You can try using left join too 您也可以尝试使用左联接
INSERT INTO star_ratings(post_id)
SELECT postid FROM posts left join star_ratings on posts.postid=star_ratings.post_id
WHERE type in ('D', 'B') and star_ratings.post_id is null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.