代码之家  ›  专栏  ›  技术社区  ›  Code Lover

如果postid不存在,MySQL将记录插入一个表到另一个表

  •  0
  • Code Lover  · 技术社区  · 7 年前

    如果我想插入,有没有比这更好的方法来编写查询 postid 从…起 posts 表到 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
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Tim Biegeleisen    7 年前

    以下 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);
    
        2
  •  0
  •   Fahmi    7 年前

    你也可以尝试使用左连接

    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