views:

61

answers:

2

I have a mysql problem. I have two tables like this that I need to join together.

table:

id otherid2
1 | 1
2 | 1
3 | 2
4 | 2

table2:

otherid otherid2
1 | 1
2 | 1
3 | 2
4 | 2

I'm using:

SELECT id,otherid FROM table INNER JOIN table2 ON table.otherid2=table2.otherid2

This gives me:

id otherid
1 | 1
1 | 2
2 | 1
2 | 2
3 | 3
3 | 4
4 | 3
4 | 4

As you can see I get duplicates of id as there is otherid2s that is not unique in table2. What I need is to INNER JOIN DISTINCT in some way, I only want the result to be as below. Not duplicates.

This is what I want:

id otherid
1 | 1
2 | 1
3 | 3
4 | 3

Can I do this in an easy way?

A: 

In your comment you wanted the lowest, then I'd suggest a group by and a min aggregator

SELECT id, MIN(otherid) AS otherid ... GROUP BY id
myme
+1  A: 

If you want the row with the lowest id in table2, this should probably do it

SELECT id, min(otherid)
FROM table 
INNER JOIN table2 
ON table.otherid2=table2.otherid2
GROUP BY id
InSane
Thanks! I must be very tired today.. :)
Martin
@Martin - Agree :-) When you miss something like that, its time to go home!! :-)
InSane
@InSane - I totally agree, thanks anyway! :)
Martin