douchixu3686 2017-01-05 14:11
浏览 53

如何使用MYSQL在结果中将0值设为NULL

I have a query that selects a list of customers, and how many times we have performed a service, which I can reset whenever I want. When we have not been there, the value shows up as zero, when I would rather it just not show up at all. How can I do this?

here is the code:

$query = "  SELECT * 
            FROM customers b
            JOIN customerRoutes a
            ON a.customerPK=b.customerPK
            WHERE a.inches <= $inches
            AND a.routesPK = $route_name
            AND $day
            AND b.active=1
            ;";

$result = mysqli_query($con,$query);
    echo "<table border='1'><tr><th>Customers</th><th>Times Visited</th>
                                </tr>";

while($row    = mysqli_fetch_assoc($result))
  {
  echo "<tr>";
  echo "<td> <a href='snow.php?technician=".$technician."&customer=".$row['customerName']."&route=".$row['routesPK']."&service=".$newService."&customerPK=".$row['customerPK']."' target='iframe_a' >".$row['customerName']."</a></td>";
  echo "<td>".$row['occurences']."</td>";
  echo "</tr>";
  }

The trouble is near the bottom, its "OCCURENCES". I've tried using NULLIF but I'm not sure where it should go properly. Any help is appreciated.

  • 写回答

1条回答 默认 最新

  • dongzi5062 2017-01-05 14:17
    关注

    You can either do it using PHP, e.g.

    echo "<td>" . ($row['occurences'] > 0 ? $row['occurences'] : "") . "</td>";
    

    or you can use SQL as @spencer7593 suggested

    SELECT b.customerName, b.customerPK, NULLIF(b.occurrences,0) AS occurrences, ...
    

    As an alternative, you can try the standard case statement

    select b.customerName, b.customerPK,
           case b.occurrences when 0 then null else b.occurrences end
    from customers b
    

    Unrelated, but you should not use select *, rather be explicit and name each column, e.g. select customerName, occurences, ....

    评论
    编辑
    预览

    报告相同问题?

    手机看
    程序员都在用的中文IT技术交流社区

    程序员都在用的中文IT技术交流社区

    专业的中文 IT 技术社区,与千万技术人共成长

    专业的中文 IT 技术社区,与千万技术人共成长

    关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

    关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

    客服 返回
    顶部