单表重新安置亲属

时间:2016-10-03 21:47:08

标签: mysql sql self-join

不能说它不那么令人困惑,对不起...... 想象一下DB表有3列:

  • object_id - 某个实体,
  • relation_key - 对象的某些属性,
  • bundle_id - 我们必须使用此ID推广不同的对象。

表格[ object_id relation_key ]的唯一键: 单个对象不能有重复的 relation_key , 但是不同的对象可以具有相等的 relation_key

对图片的一些氧气理解: enter image description here

很多对象可以通过relation_key建立深层关系,所有这些对象都与 bundle_id

相关联

如何使用单个查询更新正确值的bundle_id列? 我可以写程序,但这种方式不适合我。

我寻找的声明如下:
“UPDATE示例[连接示例ON ...] SET bundle_id = ... WHERE ...”

mysql的“before”架构:

CREATE TABLE `example` (
  `bundle_id` INT(11) DEFAULT NULL,
  `object_id` INT(11) NOT NULL,
  `relation_key` INT(11) NOT NULL,
  PRIMARY KEY (`object_id`,`relation_key`) 
);

INSERT INTO `example`(`object_id`, `relation_key`) 
VALUES (1, 4), (1, 5), (1, 6), (2, 6), (2, 7), (2, 8), (3, 4), 
(3, 9), (3, 10), (4, 11), (4, 12), (4, 13), (5, 14), (5, 15), (5, 16), (6, 17), (6, 11), (6, 18);

以下是“之前”的示例:fiddle example(此时此刻已停滞不前)

如果你进行查询,“之后”会像是一样:

UPDATE `example` SET `bundle_id` = 1 WHERE `object_id` IN (1, 2, 3);
UPDATE `example` SET `bundle_id` = 2 WHERE `object_id` IN (4, 6);
UPDATE `example` SET `bundle_id` = 3 WHERE `object_id` IN (5);

object1 related to object2 by key=6, 
object3 related TO object1 by key=4, 
so ... objs 1, 2, 3 are related together. 
here must be first bundle_id=1. 
there is no other keys linking another objects to 1, 2, 3

object_id=4 related to object_id=6 by key=11
so ... obj [4, 6] are related together. 
here must be second bundle_id=2, 
there is no other keys linking another objects to 4, 6  

object_id=5 has no relations to other objects
all object's key belong to itself. 
here must be second bundle_id=3, 
there is no other keys linking another objects to 5   

0 个答案:

没有答案