Mysql(PHP):删除SUM = 0的所有行

时间:2015-03-19 16:29:19

标签: php mysql

我有这张桌子

+----+--------+
| id | amount |
+----+--------+
|  1 |     10 |
|  2 |      5 |
|  3 |     -5 |
|  4 |      6 |
|  5 |    -16 |
|  6 |      4 |
|  7 |      1 |
|  8 |     -3 |
+----+--------+

我需要删除所有行(按照从最小ID到最大ID的顺序),使SUM = 0。

在我的例子中,如果我们划分表,我需要删除id 1,2,3,4,5因为它们的SUM = 0(10 + 5-5 + 6-16),但是留下记录6 ,7,8-

我不知道如何编写查询,阅读步骤中的步骤。

谢谢

2 个答案:

答案 0 :(得分:1)

DELETE a  
  FROM my_table a 
  JOIN 
     ( SELECT x.*
            , SUM(y.amount) running 
         FROM my_table x 
         JOIN my_table y 
           ON y.id <= x.id 
        GROUP 
           BY x.id
     ) b 
    ON b.id >= a.id 
 WHERE b.running = 0;

答案 1 :(得分:0)

PHP-ish伪代码:

$data = get_data();
list($minID, $maxID, $currSum) = array($data[0]['id'], 0, 0);
foreach ( $data as $value ) {
  $currSum += $value['amount'];
  if ( !$currSum ) {
    $maxID = $value['id'];
    break;
  }
}
$sql = "DELETE FROM table WHERE id >= $minID AND id <= $maxID";