【问题标题】:Select everything from SQL database except duplicate从 SQL 数据库中选择除重复项之外的所有内容
【发布时间】:2020-09-01 14:30:07
【问题描述】:

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

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】:

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   |

【讨论】:

    猜你喜欢
    • 2012-02-24
    • 2012-08-05
    • 2016-01-11
    • 2010-09-07
    • 2021-01-25
    • 1970-01-01
    • 2016-11-03
    • 2017-03-28
    • 1970-01-01
    相关资源
    最近更新 更多