使用WHERE将值从一个表复制到另一个表

时间:2016-08-24 18:16:37

标签: mysql

我有两个表,我想从一个表添加信息到另一个表,但表有相同的行。

INSERT INTO wp_posts ( 
      id, 
      post_author, 
      post_content, 
      post_title,
      post_name,
      post_type
            ) 
SELECT  id, 
      3, 
      post_content, 
      post_title,
      post_name,
      post_type
FROM wp_posts2
WHERE  post_type='Vacancy'

所以我收到错误

[Err] 1062 - Duplicate entry '7142' for key 'PRIMARY'

如何只添加新行?

2 个答案:

答案 0 :(得分:0)

只获取新ID:

INSERT INTO wp_posts ( 
      id, 
      post_author, 
      post_content, 
      post_title,
      post_name,
      post_type
            ) 
SELECT  id, 
      3, 
      post_content, 
      post_title,
      post_name,
      post_type
FROM wp_posts2
WHERE  post_type='Vacancy'
and id not in (select id from wp_posts)

答案 1 :(得分:0)

在我看来,在表中wp_posts id是主键,wp_posts2具有相同的id值。这就是它抛出错误的原因。

如果id是AUTO_INCREMENT字段,那么您不需要在查询中包含“id”,如下所示:

INSERT INTO wp_posts ( 
  post_author, 
  post_content, 
  post_title,
  post_name,
  post_type
        ) 
SELECT 
  3, 
  post_content, 
  post_title,
  post_name,
  post_type
FROM wp_posts2
WHERE  post_type='Vacancy'
相关问题