gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:59:04 25 4
gpt4 key购买 nike

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

我有一个包含两列的表格,显示哪些 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。在那种情况下,有谁知道包含递归的解决方案吗?

最佳答案

如果您对任何连接的 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

关于mysql - SQL:为具有多个 ID 的项目创建唯一 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11139072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com