mysql - 如何从此表中选择多个实例?
问题描述
所以我有这张桌子
|---------------------|------------------|------------------
| 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)。
解决方案
你没有提到你使用的是哪个 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
推荐阅读
- asp.net - 如何在 asp.net api 响应中包含嵌套列表
- r - 根据 ID 选择数据行
- c# - 关于通过协程暂停 if 语句的问题
- python - 按小写先大写再数字的顺序排序,然后将数字排序为奇数不优先
- php - 我想从 Prestashop 打开我的管理面板,但出现此错误:尝试从全局命名空间调用函数“simplexml_load_string”
- java - Java中的条件运算符,我不希望假布尔值做任何事情
- python - Pandas 删除对一列具有不同值的行,但对所有其他列重复
- php - ChromeOptions 不工作 - PHP WebDriver
- python - 给定一组索引,在数据框中的每个索引之间聚合
- nestjs - 内连接以获取 typeorm 中的平均值