我有一个看起来像这样的数据库:
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 |
-----------------------------------
它测量participant1
和participant2
握手了多少次。我想选择总人数与他人握手的次数(不计重复次数)。因此,在此示例中,输出将如下所示:
Thomas Miller | Max Miller
Thomas Miller | Jack Miller
Jack miller | Max Miller
Total: 3times
任何人都可以通过SQL语句帮助我吗?
使用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 |