1

I have this query in 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

The problem is that it returns more data than I need:

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

I only need rows 1 and 3, or rows 2 and 4.

3 Answers 3

5
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
  ;

Or with the much hipper JOIN-syntax:

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
  ;
Sign up to request clarification or add additional context in comments.

3 Comments

It seems to work. And do I understand it right: When you have the smaller than sign one of the two rows are left out, because one of the two must have a value bigger than the other. Thats the idea right?
You want to find pairs with the same title. But the original query finds items that are part of such a pair. And for every pair there are two such members, so you can choose an arbitrary way of supressing one of the two pair-members, such as p1.id < p2.id
But you should realise that if there are more then two members of a same-title group, the result will still show more than one row (eg, for triplets: it will show {1,2} and {2,3} and {1,3})
0

I have simple idea to implement your scenario.

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

Comments

0
select DISTINCT p1.id, p2.id, p1.title, p2.title 
from publication "p1", publication "p2"
where p1.title = p2.title

1 Comment

Please add some explanation along with your code to help the OP solve her/his problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.