我试图运行查询我phpmyAdmin如下
SELECT
orders_history.id,
orders_history.`items`,
orders_history.`transaction_id`,
orders_history.`quantity`,
estockClaims.`esquantity`,
IFNULL( esquantity, 0 ),
orders_history.`quantity` - estockClaims.`esquantity` AS myquantity
FROM orders_history
LEFT JOIN estockClaims
ON orders_history.transaction_id = estockClaims.transaction_id
AND orders_history.items = estockClaims.items
LIMIT 0 , 100
它给了我这个结果:
----------------------------------------------------------------------
id items transaction_id quantity esquantity IFNULL(esquantity , 0 ) myquantity
1 FR 001 100 NULL 0 NULL
2 BR 002 10 NULL 0 NULL
3 WR 003 25 25 25 0
4 CR 004 50 3 3 47
如何解决这个问题,以便NULL不是NULL,而是更改为0.提前感谢。
由于
答案 0 :(得分:4)
您已在下一栏中找到它。您需要做的是删除原始esquantity
列并为IFNULL...
列创建别名,如下所示:
SELECT orders_history.id, orders_history.`items` , orders_history.`transaction_id` ,
orders_history.`quantity` , IFNULL( esquantity, 0 ) AS esquantity,
orders_history.`quantity` - estockClaims.`esquantity` AS myquantity
FROM orders_history
LEFT JOIN estockClaims ON orders_history.transaction_id = estockClaims.transaction_id
AND orders_history.items = estockClaims.items
LIMIT 0 , 100
我提到的改变在上面第2行。
更新
获得
orders_history.`quantity` - estockClaims.`esquantity` AS myquantity
要显示预期结果,您需要" unnullify"再次esquantity
字段,以便减法可行:
orders_history.`quantity` - IFNULL( estockClaims.`esquantity`, 0 ) AS myquantity
这将确保您不再获得,例如:
100 - NULL
但请改为:
100 - 0
将返回正确的值。
如果esquantity
为NULL并且只使用quantity
的值,您也可以跳过整个减法事项。
答案 1 :(得分:0)
您可以使用IF
查看esquantity
和myquantity
列:
IF(esquantity IS NULL, 0, esquantity)
和
IF(myquantityIS NULL, 0, myquantity)
或使用IFNULL
作为DanFromGermany说
答案 2 :(得分:0)
原因是您使用它作为选择而不是在进行减法时。使用方法如下:
SELECT orders_history.id, orders_history.`items` , orders_history.`transaction_id` , orders_history.`quantity` , orders_history.`quantity` - IFNULL( esquantity, 0 ) AS myquantity
FROM orders_history
LEFT JOIN estockClaims ON orders_history.transaction_id = estockClaims.transaction_id
AND orders_history.items = estockClaims.items
LIMIT 0 , 100
答案 3 :(得分:0)
select temp.id, items, transaction_id, quantity, ifNULL(esquantity, 0), ifNULL(myquantity, 0)
from (SELECT
orders_history.id,
orders_history.`items`,
orders_history.`transaction_id`,
orders_history.`quantity`,
estockClaims.`esquantity`
orders_history.`quantity` - estockClaims.`esquantity` AS myquantity
FROM orders_history
LEFT JOIN estockClaims
ON orders_history.transaction_id = estockClaims.transaction_id
AND orders_history.items = estockClaims.items
LIMIT 0 , 100) temp
答案 4 :(得分:0)
您还可以使用 COALESCE 将 NULL值替换为0
检查此查询。
SELECT orders_history.id, orders_history.`items` , orders_history.`transaction_id` ,
orders_history.`quantity` , COALESCE( esquantity, 0 ) AS esquantity,
orders_history.`quantity` - COALESCE(estockClaims.`esquantity`, 0) AS myquantity
FROM orders_history
LEFT JOIN estockClaims ON orders_history.transaction_id = estockClaims.transaction_id
AND orders_history.items = estockClaims.items
LIMIT 0 , 100