简体   繁体   English

如何使用 SQL 表中的唯一元素对 select

[英]How to select unique pairs of elements in a table with SQL

I have an table of people where each person can have a associate partner like this:我有一张桌子,每个人都可以有一个这样的合伙人:

id_person id_person Name姓名 id_partner id_partner
1 1 Javi哈维 5 5
2 2 John约翰 4 4
3 3 Mike麦克风 6 6
4 4 Lucy露西 2 2
5 5 Jenny珍妮 1 1
6 6 Cindy辛迪 3 3

So I would like to have a query where I can get all the couples without repetance like所以我想问一个问题,我可以在哪里得到所有的夫妻而不会重复,比如

Name 1名称 1 Name 2名称 2
Javi哈维 Jenny珍妮
John约翰 Lucy露西
Mike麦克风 Cindy辛迪

I now how I would do it in python but in sql I have no clue我现在如何在 python 但在 sql 我不知道

Thank you in advance!!!先感谢您!!!

In SQL we solve these problems using a self inner join which is when we create a temporary alias of the table and join the table to its alias.在 SQL 中,我们使用自内连接解决了这些问题,这是当我们创建表的临时别名并将表连接到其别名时。 The join condition would be two different columns, one from each table being equal to each other.连接条件将是两个不同的列,每个表中的一个列彼此相等。

This allows you to make pairs of columns from single columns, but all of the rows will be duplicated in a backwards representation.这允许您从单列创建成对的列,但所有行都将以向后表示形式复制。 To get rid of those, you need a filter where you compare one column to be less than the corresponding column in the other table.要摆脱这些,您需要一个过滤器,您可以在其中比较一列小于另一表中的相应列。

As the condition implies, it means one set of people's IDs must all be less than the IDs of all of the partners.正如条件所暗示的,这意味着一组人的 ID 必须都小于所有合作伙伴的 ID。

This is how you'd write the query for your table:这是您为表编写查询的方式:

SELECT Table1.Name AS "Name 1", Table2.Name AS "Name 2" FROM Table1 INNER JOIN (Table1) Table2 ON Table1.id_person = Table2.id_partner WHERE Table1.id_person < Table2.id_person

And then if you want you can order by either of the Name columns to sort the output.然后,如果您愿意,可以按任一名称列排序 output。

SELECT t2.[Name] AS Name1, t1.[Name] AS Name2 from Table_Name t1 INNER JOIN Table_Name t2 ON t2.id_partner = t1.id_person SELECT t2.[Name] AS Name1, t1.[Name] AS Name2 from Table_Name t1 INNER JOIN Table_Name t2 ON t2.id_partner = t1.id_person

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM