SQL表中记录的唯一组合(从节点表获取边)

SQL表中记录的唯一组合(从节点表获取边),sql,graph,google-bigquery,combinations,Sql,Graph,Google Bigquery,Combinations,我遇到了一个用例,我想生成一个组合表,其中记录的属性必须与表中的所有其他记录匹配。类似于使用节点表在完整图形中创建边列表 给你一个需求的例子,你可以考虑下表PrgRES. create table test_users ( id uuid default uuid_generate_v4(), first_name text, last_name text ); 我使用以下插入查询向表中添加了一些记录 INSERT INTO public.test_u

我遇到了一个用例,我想生成一个组合表,其中记录的属性必须与表中的所有其他记录匹配。类似于使用节点表在完整图形中创建边列表

给你一个需求的例子,你可以考虑下表PrgRES.

create table test_users
(
    id         uuid default uuid_generate_v4(),
    first_name text,
    last_name  text
);
我使用以下插入查询向表中添加了一些记录

INSERT INTO public.test_users (id, first_name, last_name) VALUES ('3ef309db-07cd-4e3f-95db-406f8165e54d', 'john', 'doe');
INSERT INTO public.test_users (id, first_name, last_name) VALUES ('50f33b51-1d3a-463c-9d5a-6f0b2c15cba2', 'marry', 'poppins');
INSERT INTO public.test_users (id, first_name, last_name) VALUES ('9812fbcf-d269-47a4-801d-2a8916e114e1', 'tony', 'stark');
INSERT INTO public.test_users (id, first_name, last_name) VALUES ('8d7b8d00-9602-4a12-914d-3df6a40d2716', 'idris', 'alba');
INSERT INTO public.test_users (id, first_name, last_name) VALUES ('2dee874f-f41e-4d68-a341-45e0a18079df', 'john', 'frusciante');
您将得到下表

                  id                  | first_name | last_name
--------------------------------------+------------+------------
 3ef309db-07cd-4e3f-95db-406f8165e54d | john       | doe
 50f33b51-1d3a-463c-9d5a-6f0b2c15cba2 | marry      | poppins
 9812fbcf-d269-47a4-801d-2a8916e114e1 | tony       | stark
 8d7b8d00-9602-4a12-914d-3df6a40d2716 | idris      | alba
 2dee874f-f41e-4d68-a341-45e0a18079df | john       | frusciante
现在我想创建这些名称的组合,这样行的第一个名称就应该有所有可能的组合,这样f1,f2=f2,f1。为了给您提供更多的上下文,预期的输出应该如下所示

 first_name | first_name | last_name  | last_name
------------+------------+------------+------------
 john       | marry      | doe        | poppins
 john       | tony       | doe        | stark
 john       | idris      | doe        | alba
 john       | john       | doe        | frusciante
 marry      | tony       | poppins    | stark
 marry      | idris      | poppins    | alba
 marry      | john       | poppins    | frusciante
 tony       | idris      | stark      | alba
 tony       | john       | stark      | frusciante
 idris      | john       | alba       | frusciante
您可以看到表中first_name的第1列和第2列的组合是唯一的

我能找到的最接近的方法是使用以下查询进行内部连接

select t1.first_name,
    t2.first_name,
    t1.last_name,
    t2.last_name
from test_users t1
        left join test_users t2 on t1.id <> t2.id;
但这会产生所有记录,其中f1,f2!=f2,f1,因此创建冗余记录。有没有一种方法可以使用SQL从完整图形中的节点列表中获取唯一的边列表?

只需使用,而不是在连接条件中使用:

select 
    t1.first_name first_name1, 
    t2.first_name first_name2, 
    t1.last_name last_name1, 
    t2.last_name last_name2
from test_users t1
inner join test_users t2 on t1.id < t2.id
注:

您可能希望在resultset中对列进行别名,以消除来自这两个表的列的歧义

不需要左连接-内部连接可以满足您的需要


在联接中使用t1.id