首页 > 解决方案 > 如何从此表中选择多个实例?

问题描述

所以我有这张桌子

|---------------------|------------------|------------------
|          id         |      sender      |     recipient
|---------------------|------------------|------------------
|          1          |       Luke       |       Josh
|---------------------|------------------|------------------
|          2          |       Josh       |       Luke
|---------------------|------------------|------------------
|          3          |       Phil       |       Sam
|---------------------|------------------|------------------
|          4          |       Sam        |       Phil
|---------------------|------------------|------------------
|          5          |       Sam        |       Luke
|---------------------|------------------|------------------

给定一个名称,我只想选择与不同用户的每次交互的一个实例。例如,给定名称“Luke”,我希望选择行 id=1 和 id=5(或 id=2 和 id=5)。

标签: mysqlsqldatabase

解决方案


你没有提到你使用的是哪个 MySQL 版本,所以我假设一个现代版本,MySQL 8.x。

您可以使用ROW_NUMBER()

select id, sender, recipient
from (
  select *,
    row_number() over(order by recipient) as rn
  from (
    select id, sender, recipient from t
    union
    select id, recipient, sender from t
  ) x
  where sender = 'Luke'
) y
where rn = 1

推荐阅读