mysql - 连接 2 个表的准确结果

标签 mysql

表 A 列出了一个元素以及必须经过 4 个可能站点中每个站点的件数。

Item      To Cut      To Paste      To Laminate      To Ship
Box          9            9              5              9
Cart         1            0              10             10

表 B 列出了每个站点已处理的件数。

Item      Cut Done      Paste Done      Laminated      Shipped
Box          9            0                0             0
Box          0            9                0             0
Box          0            0                5             0
Box          0            0                0             9

当我加入他们时,它显示:

Item      To Cut      Cut Done      To Paste      Paste Done
Box          36          9             36             9

这是因为表 B 的工作方式。我怎样才能让它在一张表中准确显示待切割和已完成的总切割量,以便百分比正确?

我的查询是:

select a.item, a.to_cut, a.to_paste, a.to_laminate, a.to_ship, b.cut_done, b.paste_done, b.laminated, b.shipped

from ToDo a join Done b on a.item = b.item

最佳答案

您应该添加一个包含计算所得总和的子查询。

select tableA.Item, To_Cut, To_Paste, To_Laminate, To_Ship, d.Cut_Done, d.Paste_Done, d.Laminated, d.Shipped
from tableA 
inner join (select Item, 
                   sum(Cut_Done) as Cut_Done,
                   sum(Paste_Done) as Paste_Done,
                   sum(Laminated) as Laminated,
                   sum(Shipped) as Shipped
            from   tableB
            group by Item) d
on tableA.Item = d.Item;

| Item | To_Cut | To_Paste | To_Laminate | To_Ship | Cut_Done | Paste_Done | Laminated | Shipped |
|-----:|--------|----------|-------------|---------|----------|------------|-----------|---------|
| Box  | 9      | 9        | 5           | 9       | 9        | 9          | 5         | 0       |

Rextester here

关于mysql - 连接 2 个表的准确结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43620491/

相关文章:

php - 哪个PHP文件占用了服务器上的mysql资源?

php - Mysql查询两列不重复

Python,删除UTF8 MySQL DB无法处理的字符,例如表情符号

mysql - 通过 MySQL 将 UTC 转换为 MDT

javascript - 使用 jQuery 和 PHP 从 MySQL 数据库查询的 JSON 数据填充 HTML 选择字段

php - 如何设置一个进程以便它在另一个进程之后执行?

javascript - 如何创建单词选择器以从文本中选择并突出显示和删除选定的单词?

Mysql 获取上个月的过程

mysql - 如何在node js中使用sequelize和mysql插入批量数据而不使用循环插入查询

php - 使用 PHP 和 MySQL 处理用户帐户使用情况