mysql 选择重复记录,选择时重复的MySQL标记记录

I have seen MySQL Mark Records with Duplicates question and answers. But I have a different situation.

How to select all records, but have a flag for those records who have duplicates in a given field.

id name

--------------

1 John

2 Peter

3 John

4 David

And I want something like that:

SELECT

id,

name,

-- IF(~duplicate in name~, 1, 0) AS is_duplicate

FROM tab

解决方案

I assume id is set to auto increment then you can use following query for your desired output

select distinct a.*,

case when b.id is null then 0 else 1 end `duplicate`

from tab a

left join tab b

on a.name = b.name

and a.id > b.id

order by a.id

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值