Sql选择sum limit ignore

时间:2014-02-20 03:42:30

标签: php mysql

我面临的情况是我需要避免查询本身内的重复数字。

我有这样的代码:

    $rangelimit     = range(6, 60, 6);
    $name            = "some name";
    foreach( $rangelimit as $limit){

       $result = $db->query("SELECT SUM(numbers) 
                  FROM (SELECT numbers FROM table WHERE name ='".$name."' 
                  ORDER BY id ASC LIMIT 0,".$limit.") 
                  AS SUBT");

        if($result)
            echo $limit.' value is .' $result;

    }// end foreach

    // outputs
    // 6 value is 22
    // 12 value is 32
    // 18 value is 40
    // but here is the problem once there is no more results 
    // i want it to stop and give 0
    // 24 value is 40
    // 30 value is 40 ... and keeps going on till 60 as set on the range.

我的问题是查询相关,因为我可以在foreach循环中停止它,但我想知道是否有任何方法可以告诉查询停止,如果没有结果达到限制?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你希望总和为0,其中限制中没有足够的行。这是一种方法:

SELECT (case when count(*) = ".$limit."
             then SUM(numbers) 
             else 0
        end)
FROM (SELECT numbers
      FROM table
      WHERE name ='".$name."' 
      ORDER BY id ASC LIMIT 0,".$limit."
     ) SUBT;