根据第一列的重复值匹配第二列的重复值

pftdvrlh  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(367)

我有一张这样的table

CREATE TABLE table1 (
  `ID` VARCHAR(100),
  `Val` VARCHAR(100),
  `Val2` VARCHAR(100)
);

INSERT INTO table1
  (`ID`, `Val`, `Val2`)
VALUES
  ('1','4788','90'),
  ('2','4788','90'),
  ('10','4788','10'),
  ('20','111','10'),
  ('30','111','10'),
  ('57','89','89111'),
  ('59','89','89111'),
  ('60','89','10'),
  ('2','900','7000'),
  ('4','900','7001');

这张table有两个条件:
val列必须是重复值,
val2列必须重复
所以我的目标是在两个条件满足时返回数据。如果val列有重复值,val2列有重复值,并且每列都在自己的行上。
我的问题是这样的

select t1.* from table1 t1
where exists (select 1 from table1 where id <> t1.id and val = t1.val)
and exists (
  select 1 from table1 
  where val = t1.val and val2 in (select val2 from table1 group by val2 having count(*) > 1)
)

结果是这样的

ID  Val Val2
1   4788    90
2   4788    90
10  4788    10
20  111 10
30  111 10
57  89  89111
59  89  89111
60  89  10

如您所见,列之间不匹配
我想结果数据是这样的

ID  Val Val2
1   4788    90
2   4788    90
20  111 10
30  111 10
57  89  89111
59  89  89111

这是我的小提琴

lhcgjxsq

lhcgjxsq1#

你需要一个 having 以及 join . 这是演示。

select 
   t.* 
from table1 t
join (
    select  
       val, val2 
    from table1 
    group by 
       val, val2 
    having count(*) > 1  
) t1 
on t.val = t1.val 
and t.val2 = t1.val2

输出:

| ID  | Val  | Val2  |
| --- | ---- | ----- |
| 1   | 4788 | 90    |
| 2   | 4788 | 90    |
| 20  | 111  | 10    |
| 30  | 111  | 10    |
| 57  | 89   | 89111 |
| 59  | 89   | 89111 |
nvbavucw

nvbavucw2#

你可以起诉group by和having for check duplicate

select  val, val2 
    from  table1 

    group by val, val2 
    having count(*) > 1

然后

select t1.* 
from table1 t1
inner join (
    select  val, val2 
    from  table1 

    group by val, val2 
    having count(*) > 1  
) t on t.val =t1.val and t.val2 = t1.val2
jdgnovmf

jdgnovmf3#

你的计划是对的 exists . 你把逻辑搞得太复杂了:

select t1.*
from table1 t1
where exists (select 1
              from table1 tt1
              where tt1.id <> t1.id and
                    tt1.val = t1.val and
                    tt1.val2 = t1.val2
             ) ;

在同一行中需要两个值的副本。因此,这是一个 exists 条款。
这是一把小提琴。

相关问题