mysql中distinct与join,INNER JOIN DISTINCT与MySQL

我有一个mysql问题.我有两张这样的桌子需要一起加入.

表:

id otherid2

1 | 1

2 | 1

3 | 2

4 | 2

表2:

otherid otherid2

1 | 1

2 | 1

3 | 2

4 | 2

我正在使用:

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

这给了我:

id otherid

1 | 1

1 | 2

2 | 1

2 | 2

3 | 3

3 | 4

4 | 3

4 | 4

正如你所看到的,我得到id的重复,因为在table2中有otherid2s不是唯一的.我需要的是以某种方式INNER JOIN DISTINCT,我只希望结果如下.不重复.

这就是我要的:

id otherid

1 | 1

2 | 1

3 | 3

4 | 3

我能以一种简单的方式做到这一点吗?

解决方法:

如果你想在table2中具有最低id的行,这可能应该这样做

SELECT id, min(otherid)

FROM table

INNER JOIN table2

ON table.otherid2=table2.otherid2

GROUP BY id

标签:mysql,inner-join,select,distinct

来源: https://codeday.me/bug/20190722/1497399.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值