【问题标题】:Selecting rows based on distinct 2 fields in postgres基于postgres中不同的2个字段选择行
【发布时间】:2012-06-24 06:01:59
【问题描述】:

我有表格消息

| id | user_id | recepient_id | message
| 1  |    1    |      2       | test1
| 2  |    1    |      2       | test2
| 3  |    2    |      1       | test3
| 4  |    3    |      1       | test4
| 5  |    3    |      2       | test5

我是 id 为 1 的用户,想要选择我所在的行是 user_id 或 recepient_id(但每个 user_id/recepient_id 对只有 1 行)。在这个例子中,我想选择 ids 为 2、4(或 1、4 或 2、3 或 2、4。没关系。只需获取 user_id/recepient_id 的 uniq 对)

我该怎么做?

【问题讨论】:

    标签: postgresql select distinct


    【解决方案1】:
    select distinct on (least(user_id, recipient_id), greatest(user_id, recipient_id))
        id, user_id, recipient_id, message
    from the_table
    where user_id = 1 or recipient_id = 1
    

    【讨论】:

      猜你喜欢
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 2012-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多