MySQLでの最長と最短の「チェーン」をゲット?

ゼリーjey:

このスキーマを考えてみます。

create table Operation(id integer, name varchar(100));
create table Pipeline(operation_in integer, operation_out integer);

Pipeline外部キーを持っているOperationsので、パイプラインは方法で、連鎖しています。operation_outNULL可能です。どのように私は、MySQLを使用して両方の最長と最短のパイプラインチェーンにおけるオペレーションの名前を得るのですか?

操作は次のようになります。

INSERT INTO Operation VALUES (1, 'operation one');

パイプラインは次のようになりますが。

INSERT INTO Pipeline VALUES (1, 2);
INSERT INTO Pipeline VALUES (2, 4);
INSERT INTO Pipeline VALUES (4, 7);
INSERT INTO Pipeline VALUES (7, NULL);

すなわち、ここで鎖は、ID 1、2、4、7と操作との線に沿って期待された結果であろう。

"operation one", "operation two", "operation four"...

研究の数時間後、私は私が探していますかなり何を解決わかりません。

任意のMySQLのバージョンが適用されます。

串刺し:

MySQLでは、あなたが必要なチェーンを見つけるために、再帰CTEを使用することができ8.xの。

例えば:

with recursive
a as (
  select
    p.operation_in,
    p.operation_out as current_out,
    o.name as op_names,
    concat('', p.operation_in) as chain,
    1 as size
  from pipeline p
  join operation o on o.id = p.operation_in
  where not exists (
    select 1 from pipeline p2 where p2.operation_out = p.operation_in
  )
  union all
  select
    a.operation_in,
    p.operation_out,
    concat(op_names, ', ', o.name),
    concat(chain, ',', p.operation_in),
    size + 1
  from a
  join pipeline p on p.operation_in = a.current_out
  join operation o on o.id = p.operation_in
),
chains as (
  select * from a where current_out is null
)
select op_names, chain, size
from chains
where size = (select max(size) from chains)  -- finds the longest one
   or size = (select min(size) from chains); -- finds the shortest one

結果:

op_names                           chain    size
---------------------------------  -------  ----
op-nine, op-six                    9,6         2
op-one, op-two, op-four, op-seven  1,2,4,7     4

私が使用したデータのスクリプトは次のとおりです。

create table operation (id integer, name varchar(100));
create table pipeline (operation_in integer, operation_out integer);

insert into operation values (1, 'op-one');
insert into operation values (2, 'op-two');
insert into operation values (4, 'op-four');
insert into operation values (6, 'op-six');
insert into operation values (7, 'op-seven');
insert into operation values (9, 'op-nine');

insert into pipeline values (1, 2);
insert into pipeline values (2, 4);
insert into pipeline values (4, 7);
insert into pipeline values (7, null);
insert into pipeline values (9, 6);
insert into pipeline values (6, null);

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=320756&siteId=1