1

我有两张桌子:

|-------------|   |-------------|
| Person      |   | Alias       |
|-------------|   |-------------|
| person_id   |   | person_id_1 |   
| person_name |   | person_id_2 |
|-------------|   |-------------|

别名表告诉我两个人是否实际上是同一个人。如果是这种情况,我想为这些人提供一个唯一的 ID。

例如: |-------------------------| | Person | |-----------|-------------| | person_id | person_name | |-----------|-------------| | 1 | Michail | |-----------|-------------| | 2 | Michail | |-----------|-------------| | 3 | Petja | |-----------|-------------|

|---------------------------| | Alias | |-------------|-------------| | person_id_1 | person_id_2 | |-------------|-------------| | 1 | 2 | |-------------|-------------|

现在我想创建一个视图,查询,你命名它,它列出了我所有的 person_ids 和这些 ids 的唯一标识符。

|-----------------------|
| Unique ID View        |
|-----------------------|
| unique_id | person_id |
|-----------------------|
| xe3rf     | 1         |
| xe3rf     | 2         |
| y23ij     | 3         |
|-----------------------|

有人可以帮助我查看唯一 ID 视图吗?我完全无知atm :-(

谢谢inb4,

迈克尔

4

1 回答 1

0

我认为您已经有了一个可用于 uniqe id 的值。您只需要强制 person_id_1 在同一个人上是唯一的。确保您没有树状引用:

1 -> 2
2 -> 3
2 -> 4

这些树状连接通常很难在 SQL 中处理。

让我们重命名person_id_1original_id和。如果你找到一个新的连接,说“5 与 3 重复”,查询表:person_id_2secondary_id

  • original_id 列上是否存在 3?如果是,请插入新连接。
  • secondary_id 列上是否存在 3?如果是,查询该行的 original_id,并插入一个新的连接。

这样你可以避免链,你想要的查询将像

select * from Alias 

正如@a_horse_with_no_name 建议的那样,您也可以简单地使用带有RECURSIVE WITH语句的查询:

WITH RECURSIVE conn(person_id_1, person_id_2) AS (
    SELECT person_id_1, person_id_2 from Alias
  UNION ALL
    SELECT Alias.person_id_1, conn.person_id_2
    FROM Alias, conn
    WHERE Alias.person_id_2 = conn.person_id_1
),
leaf_nodes AS (
  select distinct person_id_2 from Alias
)
select * 
from conn
where conn.person_id_1 NOT IN (select person_id_2 from leaf_nodes)
order by person_id_1;
于 2017-08-22T10:20:56.717 回答