SQL:为具有多个ID的项创建唯一ID

时间:2012-06-21 13:18:20

标签: mysql sql sqlite

我一直在思考这个问题,但找不到解决方案(可能很简单。)

我有一个包含两列的表格,显示哪些ID已连接,即属于同一个人。

在此示例中,只有三个人,但其中一个人有三个唯一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。在这种情况下,有没有人知道包含递归的解决方案?

1 个答案:

答案 0 :(得分:2)

如果您对连接的ID链的长度有一个上限,您可以多次自行加入表并获得所有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