首页 > 数据库 > MySQL > 在组合中找到重复的数据
挺有意思的一个需求.
实验初始化一个表.
CREATE TABLE `t` ( `id` int(11) NOT NULL AUTO_INCREMENT, `c1` int(11) DEFAULT NULL, `c2` int(11) DEFAULT NULL, `c3` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ; INSERT INTO `t` VALUES (1,1,2,3),(2,1,34,32),(3,23,42,2),(4,2,2,4),(5,2,3,3),(6,1,321,32),(7,,2,4),(8,1,2,99);
实验要求找出c1,c2,c3三个字段中,任意两个字段有重复的记录.
第一种方式
select t2.* from t t2 inner join ( select 1 type,c1 v1 ,c2 v2,count(*) from t group by c1,c2 havingcount(*)>1 union all select 2,c2,c3,count(*) from t group by c2,c3 having count(*)>1 union all select 3,c1,c3,count(*) from t group by c1,c3 having count(*)>1 ) t1 on ( case t1.type when 1 then t1.v1=t2.c1 and t1.v2=t2.c2 when 2 then t1.v1=t2.c2 and t1.v2=t2.c3 when 3 then t1.v1=t2.c1 and t1.v2=t2.c3 end );
第二种方式,需要用数字辅助表了
http://blog.itpub.net/29254281/viewspace-1362897/
select * from t where id in ( select substring_index(substring_index(idlist,',',nums.id),',',-1) fromnums, ( select nid,v,group_concat(tid) idlist from ( select t.id tid,nums.id nid, case nums.id when 1 then concat(c1,',',c2) when 2 then concat(c2,',',c3) when 3 then concat(c1,',',c3) end v from nums,t where nums.id <=3 ) t1 group by nid,v having count(*)>1 ) t2 where nums.id<=(length(idlist) - length(replace(idlist,',',''))+1) );
两种方式貌似都可以.
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-1788751/ ,如需转载,请注明出处,否则将追究法律责任。