我的以下MySQL表名为商店
id ref item_no supplier
1 10 x1 usa
2 10 x1 usa
3 11 x1 china
4 12 x2 uk
5 12 x3 uk
6 13 x3 uk
7 13 x3 uk
现在我除了输出之外的其他内容如下:
id ref item_no supplier
1 10 x1 usa
3 11 x1 china
4 12 x2 uk
5 12 x3 uk
6 13 x3 uk
正如您所看到的,item_no
x1 和 x3 具有相同的参考和供应商来源,所以我想要的是删除重复记录只保留一个item_no
!
我已将此PHP代码创建为仅SELECT
结果:
$query1 = "SELECT
DISTINCT(item_no) AS field,
COUNT(item_no) AS fieldCount,
COUNT(ref) AS refcount
FROM
store
GROUP BY item_no HAVING fieldCount > 1";
$result1 = mysql_query($query1);
if(mysql_num_rows($result1)>0){
while ($row1=mysql_fetch_assoc($result1)) {
echo $row1['field']."<br /><br />";
}
} else {
//IGNORE
}
如何将查询告诉SELECT
在创建DELETE
查询之前,根据我的需要正确复制记录。
谢谢大家
答案 0 :(得分:2)
您可以使用以下查询生成所需的结果集:
SELECT t1.*
FROM store AS t1
JOIN (
SELECT MIN(id) AS id, ref, item_no
FROM store
GROUP BY ref, item_no
) AS t2 ON t1.id > t2.id AND t1.ref = t2.ref AND t1.item_no = t2.item_no
DELETE
你可以使用:
DELETE t1
FROM store AS t1
JOIN (
SELECT MIN(id) AS id, ref, item_no
FROM store
GROUP BY ref, item_no
) AS t2 ON t1.id > t2.id AND t1.ref = t2.ref AND t1.item_no = t2.item_no
答案 1 :(得分:1)
要查找只能使用的重复记录
SELECT * FROM store WHERE id NOT IN
(SELECT id FROM store AS outerStore WHERE id =
(SELECT MAX(id) FROM store AS innerStore
WHERE outerStore.ref = innerStore.ref AND
outerStore.supplier = innerStore.supplier AND outerStore.item_no = innerStore.item_no))
也许很长,但它应该有效。
答案 2 :(得分:0)
如果要删除选择行,请使用
select * from store
where id not in (
select max(id) from store
group by distinct ref, item_no, supplier);
或者您可以使用
直接使用命令进行直接删除delete from store
where id not in (
select max(id) from store
group by distinct ref, item_no, supplier);