Domanda

I just wanna ask if is it possible to make a query to see all the duplicate items between two tables? I've tried some solutions but it returns duplicated rows not duplicated items.

For example, I have these two tables:

table_a

| A | B | C | D |

..........................................

| door | book | keys | shoe |

| door | bags | desk | keys |

| rice | fish | cake | shoe |

table_b

| A | B | C | D |

| tape | fans | robe | spec |

| keys | shoe | fans | room |

| hall | pops | door | disc |

So, in the end it only returns all the items that has duplicates. For example,

| door |

| keys |

| shoe |

.....

I've tried a few queries but I still can't find a solution. Thanks.

È stato utile?

Soluzione

You can do this by unpivoting the data and using group by:

select col
from (select a as col from table_a union all
      select b from table_a union all
      select c from table_a union all
      select d from table_a union all
      select a from table_b union all
      select b from table_b union all
      select c from table_b union all
      select d from table_b
     ) t
group by col
having count(*) > 1;

If the table is large, there are more efficient ways to unpivot than using union all.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top