当COUNT = 0时,SELECT CASE与COUNT无输出

时间:2015-09-24 21:58:53

标签: php mysql

我正在尝试计算不同价格范围的广告,但是当count为零时我的查询不输出,因此我无法将其与范围数组相关联。

像这样:

这是价格中断的数组:

$arr_pri = array(1, 30000, 50000, 75000, 100000, 125000, 150000, 175000, 200000, 300000, 400000);

这是查询:

$ctpri = count ($arr_pri);

$ctmod_pri = array();

$arr_i=$arr_k='';

$sql = "SELECT `range`, COUNT(`ad_id`) as ctads FROM (
        SELECT CASE ";
         for ($i=0; $i < $ctpri-1; $i++){
            $k=$i+1;
            $arr_i=$arr_pri[$i]+1;
            $arr_k=$arr_pri[$k];

$sql .= "WHEN price BETWEEN {$arr_i} AND {$arr_k} THEN CAST('{$i}' AS UNSIGNED) ";}

$sql .= " END AS `range`, ad_id FROM ads
WHERE published = 'Y'
AND deleted = 'N' ) AS t GROUP BY `range`";
$stmt = $ulink->prepare($sql);
$stmt->execute();
while ($r = $stmt->fetch(PDO::FETCH_ASSOC)) {
    ctmod_pri[] = $r['ctads'];
}

$ ctmod_pri的典型输出是:

array(5) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "1" [3]=> string(1) "1" [4]=> string(1) "1" } 

我期待它生成一个包含10个元素的数组,每个价格范围一个(0-30000,30001-50000 ....),也输出零结果。

我错过了什么?

1 个答案:

答案 0 :(得分:1)

正如Michael-sqlbot指出的那样CASE不会做你想要的。我不完全确定所需的输出,但请尝试此查询。

SELECT '2-30000' AS `range`, SUM(CASE WHEN price BETWEEN 2 AND 30000 THEN 1 ELSE 0 END) AS `ctads` FROM ads
union
SELECT '30001-50000' AS `range`, SUM(CASE WHEN price BETWEEN 30001 AND 50000 THEN 1 ELSE 0 END) AS `ctads` FROM ads
union
SELECT '50001-75000' AS `range`, SUM(CASE WHEN price BETWEEN 50001 AND 75000 THEN 1 ELSE 0 END) AS `ctads` FROM ads
union
SELECT '75001-100000' AS `range`, SUM(CASE WHEN price BETWEEN 75001 AND 100000 THEN 1 ELSE 0 END) AS `ctads` FROM ads
union
SELECT '100001-125000' AS `range`, SUM(CASE WHEN price BETWEEN 100001 AND 125000 THEN 1 ELSE 0 END) AS `ctads` FROM ads
union
SELECT '125001-150000' AS `range`, SUM(CASE WHEN price BETWEEN 125001 AND 150000 THEN 1 ELSE 0 END) AS `ctads` FROM ads
union
SELECT '150001-175000' AS `range`, SUM(CASE WHEN price BETWEEN 150001 AND 175000 THEN 1 ELSE 0 END) AS `ctads` FROM ads
union
SELECT '175001-200000' AS `range`, SUM(CASE WHEN price BETWEEN 175001 AND 200000 THEN 1 ELSE 0 END) AS `ctads` FROM ads
union
SELECT '200001-300000' AS `range`, SUM(CASE WHEN price BETWEEN 200001 AND 300000 THEN 1 ELSE 0 END) AS `ctads` FROM ads
union
SELECT '300001-400000' AS `range`, SUM(CASE WHEN price BETWEEN 300001 AND 400000 THEN 1 ELSE 0 END) AS `ctads` FROM ads;

它将计算给定价格范围内的广告数量。您可以将2-30000更改为0,依此类推,如果这是您需要的输出。

THEN 1 else 0基本上意味着如果行满足WHEN部分,则表示添加1,否则添加0。