在MySQL中删除除一列之外的所有列匹配的行

时间:2017-11-30 15:22:33

标签: python mysql database

我有下表:

id | name  | time      | action | entered
---+-------+-----------+--------+--------
 1 | james | today     | x      |
 1 | james | today     | x      | yes
 1 | james | today     | y      |
 1 | james | today     | y      | yes
 2 | carl  | today     | x      | 
 2 | carl  | today     | y      |
 3 | casey | yesterday | x      |
 3 | casey | yesterday | x      | yes
 3 | casey | yesterday | y      |
 3 | casey | yesterday | y      | yes
 4 | john  | today     | x      | yes

我想删除entered的值为“是”的行,并且除了entered之外的所有其他列都有另一行具有相同的值。

在上面的示例中 - 应删除行2,4,8,10。

所有五个列都有一个主键

我怎样才能做到这一点? MySQL或Python 中的解决方案将被接受。

2 个答案:

答案 0 :(得分:1)

试试这个:

DELETE t1
FROM tablename AS t1
JOIN (
  SELECT id, `name`, `time`, `action`, count(*) AS cnt
  FROM tablename
  GROUP BY id, `name`, `time`, `action`
  HAVING cnt > 1
) AS t2 ON t1.id = t2.id
AND t1.entered = 'yes'
;

只需将tablename替换为您的桌子......

答案 1 :(得分:0)

我很自信,我建议你在测试之前做好备份......

DELETE x 
  FROM my_table x 
  JOIN my_table y 
    ON y.id = x.id
   AND y.name = x.name
   AND y.time = x.time
   AND y.action = x.action
   AND y.entered <> x.entered
 WHERE x.entered = 'yes';