开发者

INNER JOIN DISTINCT with MySQL

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,otheri开发者_运维问答d 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?


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜