1

私はしばらくの間この問題を熟考していて、解決策を見つけることができません(それは簡単かもしれません)。

どのIDが接続されているか、つまり同じ人物に属しているかを示す2つの列を持つテーブルがあります。

この例では、個人は3人しかいませんが、そのうちの1人は3つの一意のIDを持っています。

PID      | EPID
---------+--------
10004835 | 10004835
10015375 | 10015375
10015375 | 10019859
10019859 | 10015375
10019859 | 10019859
10019859 | 10000000
10000000 | 10019859
10020104 | 10020104

私がやりたいのは、このテーブルに列を追加して、各個人に固有のコードを与えることです。それは次のようなものです

PID      | EPID     | NPID
---------+----------+-----
10004835 | 10004835 | 1
10015375 | 10015375 | 2
10015375 | 10019859 | 2
10019859 | 10015375 | 2
10019859 | 10019859 | 2
10019859 | 10000000 | 2
10000000 | 10019859 | 2
10020104 | 10020104 | 3

追伸 私はsqlite3を使用しているので、回答の再帰はありません。

編集:SQLITE3で機能するソリューションが見つからない限り、代わりにMYSQLを使用する必要があります。その場合、再帰を含む解決策を知っている人はいますか?

4

1 に答える 1

2

接続されたIDチェーンの長さに上限がある場合は、テーブルに何度も自己参加して、すべてのIDの最小(または最大)を取得できます。

select pid, epid,
  min(t1.epid,
      coalesce(t2.epid, t1.epid),
      coalesce(t3.epid, t1.epid),
      coalesce(t4.epid, t1.epid),
      coalesce(t5.epid, t1.epid)) npid
from table t1
join table t2 on t1.epid = t2.pid and t2.epid not in (t1.epid)
join table t3 on t2.epid = t3.pid and t3.epid not in (t1.epid, t2.epid)
join table t4 on t3.epid = t4.pid and t4.epid not in (t1.epid, t2.epid, t3.epid)
join table t5 on t4.epid = t5.pid and t5.epid not in (t1.epid, t2.epid, t3.epid, t4.epid)
group by pid, epid
于 2012-06-21T14:27:33.913 に答える