我正在尝试在表中查找重复记录,并且我有显示记录的代码,但是我需要对其进行修改,以便它也显示其他重复记录。我的示例表如下:
如您所见,表(t_sen)包含重复记录,而我有以下代码来显示重复记录:
$sql = "SELECT ID, PARA_NUMBER, TEXT FROM t_sen GROUP BY TEXT having count(*) >= 2";
$results = mysqli_query($conn, $sql) or die(mysqli_error());
while($row = mysqli_fetch_assoc($results)){
foreach($row as $column => $value){
print "$column: $value <br>";
}
print "<br>";
}
我得到的输出是:
ID | PARA_NUMBER | TEXT
----------------------------
3 | 1 | is
7 | 2 | live
但是我想要的输出是:
ID | PARA_NUMBER | TEXT
----------------------------
3 | 1 | is
4 | 1 | is
7 | 2 | live
8 | 2 | live
我希望它在定义的PARA_NUMBER中也显示另一个重复的列。因此,一个示例(伪造的?)查询将类似于:
SELECT ID, PARA_NUMBER, TEXT FROM t_sen (WITHIN PARA_NUMBER = 1) having count(*) >= 2
因此输出应为:
ID | PARA_NUMBER | TEXT
----------------------------
3 | 1 | is
4 | 1 | is
但是如果我不必对每个PARA_NUMBER重复查询,那会更好得多,因为有很多数字,只有一个查询可以显示所有重复的记录。
希望我很清楚。任何帮助将不胜感激。
答案 0 :(得分:0)
此查询将执行您想要的操作。它使用子查询查找表中具有重复项的TEXT
的所有值,并将这些值联接到原始表中,以便您可以显示具有重复TEXT
值的每个条目。
SELECT ID, PARA_NUMBER, t1.TEXT FROM
t_sen t1
JOIN (SELECT TEXT
FROM t_sen
GROUP BY TEXT
HAVING COUNT(*) >= 2) t2
ON t1.TEXT = t2.TEXT
输出:
ID PARA_NUMBER TEXT
3 1 is
4 1 is
7 2 live
8 2 live
例如,如果只想获取PARA_NUMBER
1中的重复项,只需在末尾添加WHERE
子句:
SELECT ID, PARA_NUMBER, t1.TEXT FROM
t_sen t1
JOIN (SELECT TEXT
FROM t_sen
GROUP BY TEXT
HAVING COUNT(*) >= 2) t2
ON t1.TEXT = t2.TEXT
WHERE PARA_NUMBER = 1
输出:
ID PARA_NUMBER TEXT
3 1 is
4 1 is
修改
基于OP的要求,即能够编辑phpMyAdmin中的行,带有JOIN
的查询无法解决问题。而是需要这样的查询:
SELECT ID, PARA_NUMBER, t1.TEXT FROM
t_sen t1
WHERE EXISTS (SELECT *
FROM t_sen t2
WHERE t2.PARA_NUMBER = t1.PARA_NUMBER AND
t2.TEXT = t1.TEXT AND
t2.ID != t1.ID)
输出:
ID PARA_NUMBER TEXT
3 1 is
4 1 is
7 2 live
8 2 live
答案 1 :(得分:0)
我总是使用分组查找重复项。我的建议:
SELECT GROUP_CONCAT(CONCAT_WS('-', ID, PARA_NUMBER, TEXT)) AS data FROM t_sen GROUP BY PARA_NUMBER HAVING COUNT(*) > 2
这将为您提供以下格式的结果:
| data |
| 3-1-is,4-1-is |
答案 2 :(得分:0)
SELECT t.ID, t.PARA_NUMBER, t.TEXT FROM
(SELECT TEXT FROM t_sen GROUP BY TEXT having count(*) >= 2) as duplicateValue
LEFT JOIN t_sen as t on duplicateValue.TEXT = t.TEXT
WHERE 1;
答案 3 :(得分:0)
左加入
SELECT
t1.*
FROM
t_sen AS t1
LEFT JOIN
t_sen AS t2 ON t1.ID != t2.ID AND t1.PARA_NUMBER = t2.PARA_NUMBER
WHERE
t2.ID IS NOT NULL
t1.ID != t2.ID
排除了匹配两个表中的同一行(以及连接的两侧)t1.PARA_NUMBER = t2.PARA_NUMBER
将故事添加到重复的号码上WHERE t2.ID IS NOT NULL
排除不重复的记录。您还可以根据需要将TEXT
添加到联接的ON部分中,以代替PARA_NUMBER
。 / p>
只为后代
CREATE TABLE t_sen (
ID INT,
PARA_NUMBER INT,
`TEXT` VARCHAR(20)
);
#non duplate
INSERT INTO t_sen (ID, PARA_NUMBER, `TEXT`)VALUES(1,10,'the');
#duplicates
INSERT INTO t_sen (ID, PARA_NUMBER, `TEXT`)VALUES(3,1,'is');
INSERT INTO t_sen (ID, PARA_NUMBER, `TEXT`)VALUES(4,1,'is');
INSERT INTO t_sen (ID, PARA_NUMBER, `TEXT`)VALUES(7,2,'live');
INSERT INTO t_sen (ID, PARA_NUMBER, `TEXT`)VALUES(8,2,'live');
答案 4 :(得分:0)
以下查询应在PARA_NUMBER和TEXT字段上打印所有重复的记录-
SELECT ID,PARA_NUMBER,来自t_sen WHERE的文本(PARA_NUMBER,TEXT)IN (选择PARA_NUMBER,来自t_sen GROUP BY PARA_NUMBER的文本,具有count(*)> = 2的文本)