包含五个相关字段的表格;
ID (Autoincrement,unique, etc)
ID_customer - ties in each row to another table with customers, not unique, not NULL
value1 - can be 0 and NULL (NULL is not 0)
value2 - can be 0 and NULL (NULL is not 0)
type - can be 1 or 0
我想通过表格查找每个客户有多行的情况,如果有多个行在类型上具有相同的值,请删除其值列中只有0的所有行。例如;
1 1 40 8 1
2 1 0 0 1 <--
3 1 30 5 0
4 1 45 8 0
在这种情况下,命令需要删除指示的行,但保持其他行不变。不太难。像这样的东西可能会起作用(重复类型= 0):
DELETE FROM table
WHERE value1 = 0 AND value2 = 0 AND type = 1
AND ID_customer IN
(SELECT ID_customer
FROM table
WHERE type = 1 GROUP BY ID_customer HAVING count(*) > 1)
问题是这些可能存在的情况:
5 2 0 0 1
6 2 0 0 1 <--
7 2 0 0 0
8 2 0 0 0 <--
在这种情况下,我想删除两行,但不是所有行。有没有办法让我删除重复行,但只有当值列为0时?这会工作(再次,类型= 0重复),还是我错过了什么?
DELETE
FROM TABLE
WHERE value1 = 0 AND value2 = 0 AND TYPE = 1
AND ID NOT IN
(SELECT ID
FROM TABLE
WHERE value1 = 0 AND value2 = 0 AND TYPE = 1
GROUP BY ID_customer)
编辑:我已经查看了其他重复的删除问题,但我找不到以我的表所需的方式定义子查询的问题(我希望保留一些重复项)。
答案 0 :(得分:1)
所以对于第一个问题:
您对第一个问题的查询会导致错误(You can't specify target table 'table1' for update in FROM clause
但是,如果使用派生表(嵌套子查询),它可以正常工作:
DELETE
FROM table1
WHERE value1 = 0
AND value2 = 0
AND TYPE = 1
AND ID_customer IN
(SELECT ID_customer
FROM
(SELECT ID_customer
FROM table1
WHERE TYPE = 1
GROUP BY ID_customer
HAVING count(*) > 0) AS derived)
对于第二个问题,该方法非常相似,但也使用ID字段:
DELETE
FROM table1
WHERE ID IN
(SELECT dups.ID
FROM
(SELECT t1.ID
FROM table1 t1
JOIN table1 t2 ON t1.ID_Customer = t2.ID_Customer
AND t1.value1 = t2.value1
AND t1.value2 = t2.value2
AND t1.type = t2.type
AND t1.ID > t2.ID
WHERE t1.value1 = 0
AND t2.value2 =0 ) AS dups);
希望这有帮助。