计算链接中的重复项 table
Count duplicates in a linking table
我有三个table:
contacts
brands
contact_brands // linking table
就我的问题而言,我们将只处理这些(contact_id
和 brand_id
)中的 UID 列。
contact_brands
是一个链接 table,包含成对的 contact_id
和 brand_id
,我需要找到所有 duplicate 中的配对(即 contact_id
多次分配相同的 brand_id
)。
我几乎可以肯定我需要一个 SELECT * FROM (SELECT * FROM...) AS...
式的查询,并且几乎可以肯定其中也有一个 COUNT()
,但我的知识是一片空白。
您只需使用 group by
:
即可获得重复项
select contact_id, brand_id, count(*) as cnt
from contact_brands
group by contact_id, brand_id
having cnt > 1;
如果您愿意,可以重新加入以获取原始行。
如果您的链接 table 只有这两列,那么您将很难处理重复项。这可以使用自动递增的 id 来解决,如果您愿意,现在可以添加它。否则,您应该在 contact_brands(contact_id, brand_id)
上设置唯一约束或索引以防止重复。
我有三个table:
contacts
brands
contact_brands // linking table
就我的问题而言,我们将只处理这些(contact_id
和 brand_id
)中的 UID 列。
contact_brands
是一个链接 table,包含成对的 contact_id
和 brand_id
,我需要找到所有 duplicate 中的配对(即 contact_id
多次分配相同的 brand_id
)。
我几乎可以肯定我需要一个 SELECT * FROM (SELECT * FROM...) AS...
式的查询,并且几乎可以肯定其中也有一个 COUNT()
,但我的知识是一片空白。
您只需使用 group by
:
select contact_id, brand_id, count(*) as cnt
from contact_brands
group by contact_id, brand_id
having cnt > 1;
如果您愿意,可以重新加入以获取原始行。
如果您的链接 table 只有这两列,那么您将很难处理重复项。这可以使用自动递增的 id 来解决,如果您愿意,现在可以添加它。否则,您应该在 contact_brands(contact_id, brand_id)
上设置唯一约束或索引以防止重复。