user1747876
user1747876

Reputation: 55

select distinct and join?

I am looking for the most efficient way to write this query...

From table X, i need a selection of unique ids. From table Y, I need the text that go to those ids

SELECT DISTINCT ( x.id )
    FROM x

SELECT y.text
    FROM Y
    WHERE x.id = y.id

I know i can do something like this, but really slow

SELECT y.text
    FROM Y
    WHERE y.id IN ( SELECT DISTINCT ( x.id )
                        FROM x )

I've looked at some of the post about joins, but I'm unfamiliar with them. Any of you Gurus want to show me how this should be done, I'd appreciate it.

Upvotes: 0

Views: 74

Answers (2)

miken32
miken32

Reputation: 42695

How does this work? Totally off the top of my head...

SELECT x.id, y.text FROM x LEFT JOIN y USING (id) GROUP BY x.id;

Upvotes: 0

Mason T.
Mason T.

Reputation: 1577

Select y.text from y inner join 
  (Select x.id from x
   group by x.id) x
on x.id = y.id

Upvotes: 1

Related Questions