【问题标题】:Postgresql: select distinct - combinations of columnsPostgresql:选择不同的 - 列组合
【发布时间】:2013-03-10 01:26:57
【问题描述】:

我在 PostgreSQL 中有这个查询:

select p1.id, p2.id, p1.title, p2.title 
from publication "p1", publication "p2"
where p1.title = p2.title and p1.id <> p2.id

问题是它返回的数据比我需要的多:

id    id   title          title  
3456  5678 Ulysses        Ulysses  
5678  3456 Ulysses        Ulysses  
234,  345  Das Kapital    Das Kapital  
345   234  Das Kapital    Das Kapital 

我只需要第 1 行和第 3 行,或第 2 行和第 4 行。

【问题讨论】:

    标签: postgresql select distinct-values


    【解决方案1】:
    select DISTINCT p1.id, p2.id, p1.title, p2.title 
    from publication "p1", publication "p2"
    where p1.title = p2.title
    

    【讨论】:

    • 请在您的代码中添加一些解释,以帮助 OP 解决她/他的问题。
    【解决方案2】:

    我有一个简单的想法来实现你的场景。

    select p1.id, p2.id, p1.title, p2.title , sum(p1.id + p2.id) as temp
    from publication "p1", publication "p2" group by temp
    

    【讨论】:

      【解决方案3】:
      select p1.id, p2.id
       , p1.title, p2.title
      from publication p1
          , publication p2
      where p1.title = p2.title
        and p1.id < p2.id -- tie breaker
        ;
      

      或者使用更时髦的 JOIN 语法:

      SELECT p1.id, p2.id
       , p1.title, p2.title
      FROM publication p1
      JOIN publication p2 ON p1.title = p2.title
                         AND p1.id < p2.id -- tie breaker
        ;
      

      【讨论】:

      • 它似乎有效。我是否理解正确:当你有小于符号时,两行中的一列被遗漏,因为两行之一的值必须大于另一行。是这样的吗?
      • 您想查找具有相同标题的配对。但原始查询会找到属于此类配对的 items。并且对于每一对都有两个这样的成员,因此您可以选择任意方式来抑制两个对成员中的一个,例如p1.id &lt; p2.id
      • 但是你应该意识到,如果同一个标题组的成员超过两个,结果仍然会显示不止一行(例如,对于三胞胎:它会显示 {1,2}和 {2,3} 和 {1,3})
      猜你喜欢
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多