首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MySQL若条件为null

MySQL若条件为null
EN

Stack Overflow用户
提问于 2012-12-20 05:13:44
回答 1查看 1.3K关注 0票数 0

我有数据库列

表名:

  • 销售量
  • trans_details

最初,当数量分派的trans_details表被更新时,数据将被插入到trans_details表中。

销售栏

  • total_quantity
  • e.t.c

trans_details中的列

  • ordered_quantity
  • dispatched_quantity
  • pending_quantity
  • e.t.c

我想显示所有的值:- ordered_quantity - dispatched_quantity - pending_quantity

代码语言:javascript
复制
SELECT 
    IF(trans.ordered_quantity!='',trans.ordered_quantity,(sorder.total_quantity)) AS quantity,
    IF(trans.dispatched!='',trans.dispatched,0) AS today_dispatched_qty,
    IF(trans.dispatched!='',trans.dispatched,0) AS dis_qty, 
    IF(trans.Pending_quantity!='',trans.Pending_quantity,sorder.total_quantity) AS pending_qty 
FROM 
    sales as sorder 
    LEFT OUTER JOIN trans_details as trans 

该查询工作正常,但当数量完全发送它应该'0‘,但现在它显示的是total_quantity.在这种情况下,当我用'0‘代替sorder.total_quantity时,IF(trans.Pending_quantity='0',trans.Pending_quantity,sorder.total_quantity) AS pending_qty.最初它显示的是'0‘,但它应该显示total_quantity.

样本输出:

total_quantity..........dispatched_quantity.......pending_quantity

代码语言:javascript
复制
50                    45                    5
 5                     5                    0
 5                     0                    5
EN

回答 1

Stack Overflow用户

发布于 2012-12-20 14:58:12

我猜您的数据中有空值。如果问题是NULL,并且数据类型是数字的,那么尝试如下:

代码语言:javascript
复制
SELECT coalesce(trans.ordered_quantity,sorder.total_quantity) AS quantity,
       coalesce(trans.dispatched,0) AS today_dispatched_qty,
       coalesce(trans.dispatched,0) AS dis_qty, 
       coalesce(trans.Pending_quantity,sorder.total_quantity) AS pending_qty 

如果这些确实是字符串,那么您需要添加一个空检查。我鼓励您使用case,这是标准SQL,而不是if

代码语言:javascript
复制
select (case when trans.ordered_quantity is not null and trans.ordered_quantity <> ''
             then trans.ordered_quantity
             else sorder.total_quantity
       end) as quantity,
       . . .

最后,我假设您只是意外地忽略了on条款。在除MySQL之外的任何数据库中,您都会得到一个解析错误。但是,作为一种好习惯,在指定内部或外部联接时,应该始终使用on子句。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13965735

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档