Select 来自 SQL 数据库的所有内容,重复项除外

Select everything from SQL database except duplicate

我有一个如下所示的数据库:

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 握手的次数。
我想 select 总人数握手次数(不计算重复次数)。
所以在这个例子中输出将是这样的:

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   |