从SQL数据库中选择除重复项以外的所有内容

问题描述 投票:1回答:1

我有一个看起来像这样的数据库:

handshakes
-----------------------------------
|id | participant1 | participant2 |
-----------------------------------
| 1 | Thomas Miller| Max Miller   |
| 2 | Thomas Miller| Jack Miller  |
| 3 | Jack Miller  | Max Miller   |
| 4 | Max Miller   | Thomas Miller|
| 5 | Jack Miller  | Max Miller   |
-----------------------------------

它测量participant1participant2握手了多少次。我想选择总人数与他人握手的次数(不计重复次数)。因此,在此示例中,输出将如下所示:

Thomas Miller | Max Miller
Thomas Miller | Jack Miller
Jack miller   | Max Miller
Total: 3times

任何人都可以通过SQL语句帮助我吗?

sql database select sql-order-by distinct
1个回答
0
投票

使用NOT EXISTS

select id, h.participant1, h.participant2 
from handshakes h
where not exists (
  select 1 from handshakes
  where id < h.id 
  and least(participant1, participant2) = least(h.participant1, h.participant2) 
  and greatest(participant1, participant2) = greatest(h.participant1, h.participant2) 
)

此查询使用MySql和Postgresql支持的功能least()greatest()

请参见demo。结果:

| id  | participant1  | participant2 |
| --- | ------------- | ------------ |
| 1   | Thomas Miller | Max Miller   |
| 2   | Thomas Miller | Jack Miller  |
| 3   | Jack Miller   | Max Miller   |
© www.soinside.com 2019 - 2024. All rights reserved.