mysql中如何将一个表中的部分记录合并,如何在innoDB MySQL数据库中合并2条记录

I also have checked other questions and none are quite like this one.

As we know, innodb has a feature. If I want to channge an id of a record for example, then all other table that point to the previous ID will magically be updated.

What about if I want to MERGE 2 records?

Say I have 2 businesses.

They have 2 ID.

I want to merge them into one. I also want to use innodb awesome feature to automatically change things.

I can't just change one of the id to the other ID. Or can I?

What would you do to merge 2 simmilar records in database?

Of course what actually goes into the combined record will be business decisions.

Basically I just do not want to pin point all the other table one by one. I think on update rule is there for a reason. Is there a way where I just change slaveID to masterID, keep ALL data in master the same, and then have the database itself (rather than my program) to repoint all tables that point to slaveID to point to masterID? of course, records for slaveID will be gone anyway.

For example, with normal mysql engine, you can change ID, and then you have to go through all table that points to the old ID to point the new ID instead. With innodb, that repointing is done by the database engine itself. Which is kind of cool. Why would anyone use non innodb engine anyway.

I want to do the same but for merging.

解决方案

Trying to set a records primary key to an already existing value will simply result in a key violation error. While this is simple on a first glance, it has a side effect: You can not use ON UPDATE CASCADE to merge two records - it will simply not work.

If you have the possibility to change the schema, you can use the old but good redirect-trick:

(Assuming your IDs are positive, maybe unsigend ints)

add a field redirect int not null default 0

Create a view:

.

CREATE VIEW tablename_view

SELECT

-- repeat next line for every field apart from redirect

IF(s.redirect>0,m.,s.

FROM tablename AS s

LEFT JOIN tablename AS m ON s.redirect=m.id

When you merge a record (slave) into another record (master) run UPDATE tablename SET redirect= WHERE id=

Adapt your select queries to select from tablename_view instead of tablename

Create and use a maintenance script to weed out merger slaves

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值