首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在mysql简化示例中查找重复行

在mysql简化示例中查找重复行
EN

Stack Overflow用户
提问于 2012-11-08 02:46:13
回答 4查看 6.9K关注 0票数 1

自白: mysql newb需要一个简单的示例来定位有点大的表中的重复行。我已经搜索并阅读了许多具有类似标题的其他帖子,但这些例子太复杂了,我无法将它们应用于我的基本情况。

一个MySQL表只有5个字段,但是有成百上千的行。我希望找到重复的行--我知道肯定有一行,不知道是否还有其他行。

示例行:(rel_id是自动递增的,主键字段)

代码语言:javascript
复制
'rel_id' => 1
'host' => 17
'host_type' => 'client'
'rep' => 7
'rep_type => 'cli_mgr'

我的方法是:

将整个表读入mysql query

  • row-by-row将4个数据字段与以前(“”)行的数据字段进行比较
  1. 比较完“
  2. ”行后,将其附加到

的"done“行的数组中

这是我尝试过的。我相信一定有一个简单得多的解决方案。您将会看到,我在尝试将"new“行添加到"done”行的数组时陷入了困境:

代码语言:javascript
复制
$rRels = mysql_query("SELECT * FROM `rels`");
$a = array();
$e = array();
$c1 = 0;
$c2 = 0;
While ($r = mysql_fetch_assoc($rRels)) {
    $i = $r['rel_id'];
    $h = $r['host'];
    $ht = $r['host_type'];
    $r = $r['rep'];
    $rt = $r['rep_type'];

    foreach($a as $row) {
        $xh = $row['host'];
        $xht = $row['host_type'];
        $xr = $row['rel'];
        $xrt = $row['rel_type'];

        if (($h==$xh) && ($ht==$xht) && ($r==$xr) && ($rt==$xrt)) {
            echo 'Found one<br>';
            $e[] = $r;
        }
        $c2++;
    }
    $a = array_merge(array('rel_id'=>$i, 'host'=>$h, 'host_type'=>$ht, 'rep'=>$r, 'rep_type'=>$rt), $a);
    $c1++;
}

echo '<h3>Duplicate Rows:</h3>';
foreach ($e as $row) {
    print_r($row);
    echo '<br>';
}
echo '<br><br>';
echo 'Counter 1: ' . $c1 . '<br>';
echo 'Counter 2: ' . $c2 . '<br>';
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-11-08 02:54:56

这应该能起到作用:

代码语言:javascript
复制
SELECT COUNT(*) as cnt, GROUP_CONCAT(rel_id) AS ids
FROM rels
GROUP BY host, host_type, rep, rep_type
HAVING cnt > 1

任何“重复的”记录都会有一个大于1的cnt,group_concat会给你复制的记录的ids。

票数 4
EN

Stack Overflow用户

发布于 2012-11-08 03:01:01

纯粹的no-php解决方案:复制没有数据的旧表(名为oldTable)

代码语言:javascript
复制
create table newTable like oldTable;

修改结构以防止重复,并在所有5列中添加唯一键。

代码语言:javascript
复制
alter table newTable add unique index(rel_id,host,host_type,rep,rep_type );

然后使用whith查询从oldTable复制行

代码语言:javascript
复制
insert IGNORE into newTable select * from oldTable

在newTable中,您只有唯一的数据。

另一个选项是group by,如果要获取使用的重复行数

代码语言:javascript
复制
select  concat_ws('_',rel_id,host,host_type,rep,rep_type) as str, count(*) 
from oldTable 
group by str
票数 1
EN

Stack Overflow用户

发布于 2012-11-08 02:53:03

您可以使用此查询来查找所有重复的行。希望它可以很容易地集成到PHP代码中。

代码语言:javascript
复制
// This will give you all the duplicates
// Self join where all the columns have the same values but different primary keys

SELECT * 
FROM   rels t1, rels t2
WHERE  t1.rel_id != t2.rel_id
AND    t1.host = t2.host
AND    t1.host_type = t2.host_type
AND    t1.rep = t2.rep
AND    t1.rep_type = t2.rep_type
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13276128

复制
相关文章

相似问题

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