我希望从一个表中 Select 记录,或者将它们插入一个新的空白表,其中多个列与数据库中的另一个记录相同.问题与这个问题类似.

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

任何帮助都将不胜感激,我看到的所有"从MYSQL中 Select 重复项"问题都只使用一列作为比较.

推荐答案

如果要计算多个列中的重复项,请使用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

假设所有列的值都不为空,这将起作用.如果是这样,那么试试:

     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安全运算符:

     on t.ColumnA <=> tsum.ColumnA and
        t.ColumnB <=> tsum.ColumnB and
        t.ColumnC <=> tsum.ColumnC 

Mysql相关问答推荐

正则表达式转换为MYSQL格式

左联接重复问题

MySQL在使用SELECT*时不使用索引

如何在MySQL中检索两列的值不同的行

根据上一行S列结果计算列的查询

了解MySQL_stmt_BIND_NAMED_Param()-MySQL C API

使用字符串文字与使用日期文字时的SQL行为

警告:MYSQL_OPT_RECONNECT 已弃用

将 AVG 与 HAVING 结合使用

仅计算 DATEDIFF (MySQL) 中的工作日

Mysql 中相同列的相关 2 查询

如何使用减号运算符编写 sql 查询以返回缺少相应值的行?

过滤查询结果

如何计算每行的剩余金额?

查询mysql中无法识别数据值

mysql 5.5;可以从记录中排除表吗?

让 MySQL 在 OSX 10.7 Lion 上运行

如何在 MySQL 中删除此索引?

什么是全文索引,我应该什么时候使用它?

SQL WHERE 列 = 一切