将表1中第1列的数据复制到表2中的第2列,并忽略重复项

时间:2012-08-24 19:12:08

标签: mysql wordpress

我在wordpress中有一个表1

wp_term_relationships (
   object_id bigint(20),
   term_taxonomy_id bigint(20),
   term_order int(11)
)

和表2为

 wp_test (
    object_id bigint(20),
    term_taxonomy_id bigint(20)
)

现在,我尝试将wp_term_relationships中的值更新为wp_test

update ignore wp_term_relationships m1 
inner join wp_test m2
on (m1.term_taxonomy_id = m2.term_taxonomy_id)
set m1.object_id = m2.object_id

但是,wp_test的所有值都未更新为wp_term_relationships

我甚至尝试将wp_test中的值直接插入wp_test_relationships

使用插入

insert ignore into wp_term_relationships(object_id, term_taxonomy_id)
select object_id, term_taxonomy_id from wp_test

但它只是将term_taxonomy_id值更新为相应的object_id值为0或 object_id值,相应的term_taxonomy_id值为0

如何将这两列从wp_test转移到wp_term_relationships

2 个答案:

答案 0 :(得分:2)

我认为您需要的是INSERT IGNORE ON DUPLICATE KEY UPDATE代替:

INSERT INTO 
  wp_term_relationships (object_id, term_taxonomy_id)
SELECT 
  object_id, 
  term_taxonomy_id 
  FROM wp_test
ON DUPLICATE KEY UPDATE 
  wp_term_relationships.term_taxonomy_id = VALUES(term_taxonomy_id)

请注意,这假设您对wp_term_relationships.object_id有唯一约束

编辑不同的案例:

如果你的意思是构成“重复”的是两列的不同组合,那么你需要在MySQL中的两列上添加一个唯一约束,然后使用你的INSERT IGNORE查询:

ALTER TABLE wp_term_relationships ADD UNIQUE (object_id, term_taxonomy_id);

答案 1 :(得分:0)

UPDATE wp_term_relationships m1, wp_test m2
SET m1.term_taxonomy_id = m2.term_taxonomy_id
WHERE m1.object_id = m2.object_id;

我假设表格由名为“object_id”的列链接。