MySQL的单向连接和“n度分离”?

时间:2011-05-19 03:18:52

标签: mysql graph

我有一个带有整数ID的实体表,我们称之为实体。在另一个表中,我在这些实体之间有一种方式关系,它有一个“From”,“To”列和它们有什么样的关系(让我们称这个表为Relationships)。通过具有两个相应的单向关系,实体可能是“双向的”,整体事物是图形或网络。

我正在编写一个例程,我可以在其中传递一个实体ID和多少分离程度,并返回传递ID的多个关系中的每个实体ID。我不知道如何编写这个例程。这种迭代性质超出了我对存储过程的体验。任何线索如何开始这个?

2 个答案:

答案 0 :(得分:1)

对于与from_id和to_id

列的表关系
DROP PROCEDURE IF EXISTS find_relationships;
DELIMITER $$

CREATE PROCEDURE find_relationships( start_id int(11), level int(11) )
BEGIN
  DECLARE found INT(11) DEFAULT 1;
  DROP TABLE IF EXISTS related_entities;
  CREATE TABLE related_entities (id int(11) PRIMARY KEY) ENGINE=HEAP;
  INSERT INTO related_entities VALUES ( start_id );
  WHILE found > 0 AND level > 0 DO
    INSERT IGNORE INTO related_entities
      SELECT DISTINCT from_id FROM relationships r
      JOIN related_entities rf ON r.to_id = rf.id 
      UNION 
      SELECT DISTINCT to_id FROM relationships r
      JOIN related_entities rf ON r.from_id = rf.id;
    SET found = ROW_COUNT();
    SET level = level - 1;
  END WHILE;
  SELECT * FROM related_entities;
  DROP TABLE related_entities;
END;
$$
DELIMITER ;

应该适用于任何图形,找到距离给定的所有连接节点。

call find_relationships( 5, 2 );

答案 1 :(得分:0)

MySQL中没有with语句,因此您需要一个临时表。伪代码:

drop table if exists tmp_nodes;

create temporary table tmp_nodes as
select :id as id;

while :depth++ < :max_depth
  insert into tmp_nodes
  select links.id
  from links
  join tmp_nodes as nodes on nodes.id = links.parent_id
  left join tmp_nodes as cycle on cycle.id = links.id
  where cycle.id is null;

select id from tmp_nodes optionally where id <> :id;

看起来piotrm为你写了所需的功能。