0

我有数据库列


表名:

  • 销售量
  • trans_details

最初,当发送的数量trans_details表更新时,数据将插入到销售中


销售栏目

  • 总数(量
  • ETC

trans_details 中的列

  • 订购数量
  • 调度数量
  • 待定数量
  • ETC

我想显示所有值:-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……当我sorder.total_quantity在这种情况下替换为“0”时IF(trans.Pending_quantity='0',trans.Pending_quantity,sorder.total_quantity) AS pending_qty……最初它显示的是“0”,但它应该显示总数量...


样本输出:

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

50                    45                    5
 5                     5                    0
 5                     0                    5
4

1 回答 1

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 检查。我鼓励您使用case标准 SQL,而不是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在指定内连接或外连接时,您应该始终有一个子句。

于 2012-12-20T14:58:12.550 回答