首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >MySQL使用多列选择重复记录

MySQL使用多列选择重复记录
EN

Stack Overflow用户
提问于 2013-05-02 02:44:27
回答 2查看 47.5K关注 0票数 46

我希望从表中选择记录,或者将它们插入到一个新的空表中,其中多个列与数据库中的另一个记录相同。这个问题类似于这个问题。然而,Find duplicate records in MySQL只比较了一列。另外,我的其中一列,假设下面示例中的列C是一个整数。与上面链接中的问题一样,我希望返回每一行。不幸的是,我还不够熟悉joins是如何工作的,还不能自己解决这个问题。我知道下面的代码根本不像实际的SQL代码需要的,这是我所能想到的最清晰的方式来描述我试图得到的比较。

SELECT ColumnE, ColumnA, ColumnB, ColumnC from table where (
  Row1.ColumnA = Row2.ColumnA &&
  Row1.ColumnB = Row2.ColumnB &&
  Row1.ColumnC = Row2.ColumnC
)

任何帮助都将不胜感激,我所见过的所有“从MYSQL中选择重复项”的问题都只使用了一列作为比较。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-02 02:50:29

如果要对多个列中的重复项进行计数,请使用group by

select ColumnA, ColumnB, ColumnC, count(*) as NumDuplicates
from table
group by ColumnA, ColumnB, ColumnC

如果您只想要重复的值,则计数大于1。您可以使用having子句获得此结果:

select ColumnA, ColumnB, ColumnC, count(*) as NumDuplicates
from table
group by ColumnA, ColumnB, ColumnC
having NumDuplicates > 1

如果您实际上希望返回所有重复的行,则将最后一个查询连接回原始数据:

select t.*
from table t join
     (select ColumnA, ColumnB, ColumnC, count(*) as NumDuplicates
      from table
      group by ColumnA, ColumnB, ColumnC
      having NumDuplicates > 1
     ) tsum
     on t.ColumnA = tsum.ColumnA and t.ColumnB = tsum.ColumnB and t.ColumnC = tsum.ColumnC

假设没有一个列值为NULL,这将会起作用。如果是这样,那么尝试:

     on (t.ColumnA = tsum.ColumnA or t.ColumnA is null and tsum.ColumnA is null) and
        (t.ColumnB = tsum.ColumnB or t.ColumnB is null and tsum.ColumnB is null) and
        (t.ColumnC = tsum.ColumnC or t.ColumnC is null and tsum.ColumnC is null)

编辑:

如果您有NULL值,也可以使用NULL-safe运算符:

     on t.ColumnA <=> tsum.ColumnA and
        t.ColumnB <=> tsum.ColumnB and
        t.ColumnC <=> tsum.ColumnC 
票数 104
EN

Stack Overflow用户

发布于 2013-05-02 02:53:47

为什么不尝试使用联合或创建临时表。但就我个人而言,我确实建议使用union而不是创建临时表,因为这样做需要更长的时间。试着这样做:

  select field1, field2 from(
   select '' as field2, field1, count(field1) as cnt FROM list GROUP BY field2 HAVING cnt > 1
    union
    select ''as field1, field2, cound(field2) as cnt from list group by field1 having cnt > 1
  )

希望这是有意义的。:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16324328

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档