MySQL IFNULL 没有返回结果

MySQL IFNULL is not returning result

我正在尝试使用以下方法获取剩余数量的书籍

stock = total+(receive-Issued);

Table book_qnt - 图书数量列表

id  |   book    |   qnt
=======================
1   |   1       |   20  
2   |   2       |   12  

Table book - 书籍列表

id  |   ttl
===========
1   |   Social Experiment
2   |   Evolution of Culture

Table book_trns - 图书交易列表

id  |   bk  |   std |   iss |   rcv |   dte
==========================================
1   |   2   |   1   |   6   |   0   |   2019-04-11
2   |   2   |   2   |   4   |   0   |   2019-04-05

只有那些有收发值的书才可以。

DB语言中,显示book_trans.rcvbook_trans.iss不是NULL

的那些书的结果
SELECT 
book.id AS book, 
book_qnt.qnt+((SUM(book_trans.rcv))-(SUM(book_trans.iss))) AS stock,

结果

book|   stock
===========
1   |   NULL    
2   |   2

现在我尝试如下获取结果,如果 book_trans.rcvbook_trans.issNULL,那么它应该从 book_qnt 中获取总数 qnt

想要的结果

book|   stock
===========
1   |   20   // id 1's book_trans.rcv and book_trans.iss is NULL, so it should show total qnt
2   |   2    // id 2's book_trans.rcv and book_trans.iss is not NULL, so it is calculating

我做什么 如果 book_trans.rcvbook_trans.iss 行为 Null,则将值指定为 0。

SELECT 
    book.id AS book, 
    book_qnt.qnt+((IFNULL(0, SUM(book_trans.rcv)))-(IFNULL(0, SUM(book_trans.iss)))) AS stock,

但是结果(计算不起作用)

book|   qnt
===========
1   |   20
2   |   12

满MySQL

SELECT 
    book_qnt.qnt+((IFNULL(0, SUM(book_trans.rcv)))-(IFNULL(0, SUM(book_trans.iss)))) AS stock,
    lib_bk.id, 
    lib_bk.ttl 
FROM 
    book
JOIN 
    book_qnt ON book_qnt.book=book.id 
LEFT JOIN
    book_trans ON book_trans.bk=book.id
GROUP BY book.id

你在 null 测试中的 0 替换是错误的。试试这个

SELECT 
     book_qnt.qnt , SUM(book_trns.rcv), SUM(book_trns.iss),
     ((IFNULL(SUM(book_trns.rcv),0))-(IFNULL(SUM(book_trns.iss),0))),
     book_qnt.qnt+((IFNULL(SUM(book_trns.rcv),0))-(IFNULL(SUM(book_trns.iss),0))) AS stock,
    book.id, 
    book.ttl 
FROM 
    book
JOIN 
    book_qnt ON book_qnt.book=book.id 
LEFT JOIN
    book_trns ON book_trns.bk=book.id
GROUP BY book.id;

+------+--------------------+--------------------+-----------------------------------------------------------------+-------+------+----------------------+
| qnt  | SUM(book_trns.rcv) | SUM(book_trns.iss) | ((IFNULL(SUM(book_trns.rcv),0))-(IFNULL(SUM(book_trns.iss),0))) | stock | id   | ttl                  |
+------+--------------------+--------------------+-----------------------------------------------------------------+-------+------+----------------------+
|   20 |               NULL |               NULL |                                                               0 |    20 |    1 | Social Experiment    |
|   12 |                  0 |                 10 |                                                             -10 |     2 |    2 | Evolution of Culture |
+------+--------------------+--------------------+-----------------------------------------------------------------+-------+------+----------------------+
2 rows in set (0.00 sec)

并尽量使您的 table 名称与查询保持一致。