如果条件为空,则为MySQL

如果条件为空,则为MySQL,mysql,select,if-statement,Mysql,Select,If Statement,我有数据库列 表名: 销售 trans_详细信息 当发送的数量运输详情表得到更新时,最初的数据将插入到销售中 销售栏 总量 e、 t.c trans_详细信息中的列 订购数量 发货数量 待处理数量 e、 t.c 我想显示所有值: -订购数量 -发货数量 -待处理数量 SELECT IF(trans.ordered_quantity!='',trans.ordered_quantity,(sorder.total_quantity)) AS quantity,

我有数据库列


表名:

  • 销售
  • trans_详细信息
当发送的数量运输详情表得到更新时,最初的数据将插入到销售


销售栏

  • 总量
  • e、 t.c
trans_详细信息中的列

  • 订购数量
  • 发货数量
  • 待处理数量
  • e、 t.c

我想显示所有值: -订购数量 -发货数量 -待处理数量

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 
50                    45                    5
 5                     5                    0
 5                     0                    5

查询工作正常,但当数量完全调度时,它应为“0”,但现在它显示的是总数量。。。当我在这种情况下用“0”替换
sorder.total\u quantity
时,如果(trans.Pending\u quantity='0',trans.Pending\u quantity,sorder.total\u quantity)作为Pending\u quantity。。。最初显示为“0”,但应显示总数量


样本输出: 总数量…….已发送数量…….待处理数量

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 
50                    45                    5
 5                     5                    0
 5                     0                    5

我猜您的数据中有空值。如果问题为空且数据类型为数字,请尝试以下操作:

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,而不是
,如果

select (case when trans.ordered_quantity is not null and trans.ordered_quantity <> ''
             then trans.ordered_quantity
             else sorder.total_quantity
       end) as quantity,
       . . .
select(跨订单数量不为空且跨订单数量为“”时的情况)
然后按订购数量进行交易
其他分类总数量
结束)作为数量,
. . .

最后,我假设您只是意外地取消了on子句。在MySQL以外的任何数据库中,都会出现解析错误。但是,作为一个好习惯,在指定内部或外部联接时,您应该始终使用
on
子句。

添加示例数据和希望使用此输出或表数据的输出?添加表格示例数据和输出请添加正确的表格定义。我不知道为什么要在数字字段中进行字符比较?