自白: mysql newb需要一个简单的示例来定位有点大的表中的重复行。我已经搜索并阅读了许多具有类似标题的其他帖子,但这些例子太复杂了,我无法将它们应用于我的基本情况。
一个MySQL表只有5个字段,但是有成百上千的行。我希望找到重复的行--我知道肯定有一行,不知道是否还有其他行。
示例行:(rel_id是自动递增的,主键字段)
'rel_id' => 1
'host' => 17
'host_type' => 'client'
'rep' => 7
'rep_type => 'cli_mgr'我的方法是:
将整个表读入mysql query
的"done“行的数组中
这是我尝试过的。我相信一定有一个简单得多的解决方案。您将会看到,我在尝试将"new“行添加到"done”行的数组时陷入了困境:
$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>';发布于 2012-11-08 02:54:56
这应该能起到作用:
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。
发布于 2012-11-08 03:01:01
纯粹的no-php解决方案:复制没有数据的旧表(名为oldTable)
create table newTable like oldTable;修改结构以防止重复,并在所有5列中添加唯一键。
alter table newTable add unique index(rel_id,host,host_type,rep,rep_type );然后使用whith查询从oldTable复制行
insert IGNORE into newTable select * from oldTable在newTable中,您只有唯一的数据。
另一个选项是group by,如果要获取使用的重复行数
select concat_ws('_',rel_id,host,host_type,rep,rep_type) as str, count(*)
from oldTable
group by str发布于 2012-11-08 02:53:03
您可以使用此查询来查找所有重复的行。希望它可以很容易地集成到PHP代码中。
// 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_typehttps://stackoverflow.com/questions/13276128
复制相似问题