计算MySQL外部表的结果总是返回0值
我试图用2个不同的表来计数行。场景是如果tbl_task上的状态等待,此作业尚未从tbl_sales获得sales_id。一旦处理过程ID,系统将自动在tbl_sales中创建记录,并更新tbl_task for Sales_id
tbl_tasks
+----+---------+----------+
| id | status | sales_id |
+----+---------+----------+
| 1 | Waiting | NULL |
+----+---------+----------+
| 2 | Done | 19 |
+----+---------+----------+
| 3 | Process | 20 |
+----+---------+----------+
| 4 | Waiting | NULL |
+----+---------+----------+
| 5 | Cancel | NULL |
+----+---------+----------+
tbl_sales
+----------+-----+
| sales_id | qty |
+----------+-----+
| 18 | 20 |
+----------+-----+
| 19 | 18 |
+----------+-----+
| 20 | 2 |
+----------+-----+
| 21 | 7 |
+----------+-----+
| 22 | 9 |
+----------+-----+
此查询:
SELECT count(a.sales_id) total_sales, SUM(CASE WHEN b.status = 'Waiting' THEN 1 ELSE 0 END) AS total_waiting FROM tbl_sales a
LEFT JOIN tbl_tasks b ON a.sales_id = b.sales_id
返回等待等待0:
+-------------+---------------+
| total_sales | total_waiting |
+-------------+---------------+
| 5 | 0 |
+-------------+---------------+
我的预期结果是:
+-------------+---------------+
| total_sales | total_waiting |
+-------------+---------------+
| 5 | 3 |
+-------------+---------------+
任何帮助都会欣赏,我也确实会使用使用子查询,并获得了错误的结果,为total_sales(10)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里的问题是您不能加入表,因为sales_id不相关。因此,您可以使用( https:// /0 ):
但是,如果您的ID是相关的(),您可以加入数据库:
The issue here is you cannot join your tables because sales_id is not correlated. Therefore you can use (https://www.db-fiddle.com/f/mf59EiGksZEWQMbpfBwQji/0) :
However if you id were correlated (https://www.db-fiddle.com/f/2AN55gQFfE69zPoEXDnWSX/0), you could join your databases :
您仅检索未等待的销售ID 19/20。
您需要在此处加入一个正确的加入才能从任务中获取所有元素。
You are only retrieving sales id 19/20 that are not waiting.
You need a RIGHT JOIN here to get all elements from tasks.