MySQL如果条件为null

时间:2012-12-20 05:13:44

标签: mysql select if-statement

我有数据库列


表名:

  • 销售
  • 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

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_quantityIF(trans.Pending_quantity='0',trans.Pending_quantity,sorder.total_quantity) AS pending_qty ...最初它显示'0'但它应该显示total_quantity ...


样本输出:

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

50                    45                    5
 5                     5                    0
 5                     0                    5

1 个答案:

答案 0 :(得分:0)

我的猜测是你的数据中有NULL值。如果问题是NULL并且数据类型是数字,那么试试这个:

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 

如果这些确实是字符串,那么您需要添加NULL检查。我建议您使用标准SQL的case,而不是if

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子句。