从其他表插入数据并在重复键上更新

时间:2011-10-01 21:06:42

标签: mysql

我有这个查询,我想从表家中插入表exp_channel_data数据,但它插入7和8个条目,然后返回错误:

  

[Err] 1062 - 密钥'PRIMARY'重复输入'8'

这是我的查询(我将字段缩小为可读):

INSERT INTO exp_channel_data (entry_id,site_id,channel_id,field_id_1)  SELECT 7,1,1,summary FROM homes ON DUPLICATE KEY UPDATE entry_id = entry_id+1

1 个答案:

答案 0 :(得分:0)

如果要将所有homes表格数据复制到新表格中

INSERT INTO exp_channel_data 
    (entry_id, site_id, channel_id, field_id_1) 

  SELECT homes_id + (COALESCE(maxExp,0) + 1 - minHomes)
       , site_id, channel_id, summary 
  FROM homes AS h
    CROSS JOIN
      ( SELECT MAX(entry_id) AS maxExp
        FROM exp_channel_data
      ) AS mh
    CROSS JOIN
      ( SELECT MIN(homes_id) AS minHomes
        FROM exp_channel_data
      ) AS me