我正在尝试通过以下方法获取剩余图书数量
库存=总数+(已接收);
表book_qnt
-Quantiy图书清单
id | book | qnt
=======================
1 | 1 | 20
2 | 2 | 12
表book
-图书列表
id | ttl
===========
1 | Social Experiment
2 | Evolution of Culture
表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.rcv
和book_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.rcv
和book_trans.iss
为NULL
,那么它应该从qnt
获取总计book_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.rcv
和book_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
答案 0 :(得分:2)
在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)
并尝试使表名与查询保持一致。