我有来自两个零件列表的测试数据,分别称为调入和调出。在上次测试后,我需要为每个零件选择测试值的总和,其中零件进入但没有出来。
IN LIST OUT LIST TEST
+--------+-----------+ +--------+------------+ +------+-------+
| testid | in_partid | | testid | out_partid | | test | value |
+--------+-----------+ +--------+------------+ +------+-------+
| 1 | 10 | | 1 | 10 | | 1 | 1 |
| 1 | 20 | | 1 | 20 | | 2 | 10 |
| 2 | 10 | | 2 | 10 | | 3 | 100 |
| 2 | 20 | | | | | | |
| 3 | 10 | | 3 | 10 | | | |
| 3 | 20 | | 3 | 20 | | | |
+--------+-----------+ +--------+------------+ +------+-------+
SUM 非常简单,但是我可以将其限制为那些 testid 大于上次检查的 testid 的行,其中零件进入但未输出吗?
在此示例中,第 10 部分应该对所有三个测试值进行求和,因为它包含在所有列表中,但第 20 部分应该只返回测试 3 的值,因为在测试 2 中它不包含在输入和输出列表中。
partid sum(value)
10 111
20 100
我可以使用 mysql 吗,还是需要混合使用 php?
最佳答案
我认为您的示例输出从逻辑上来说是不正确的。我认为partid 20应该返回101,因为它出现在测试1和3的两个列表中。假设我是对的,这个查询应该返回所需的结果
SELECT in_partid,SUM(value)
FROM (
SELECT DISTINCT in_partid,inl.testid
FROM in_list inl
INNER JOIN out_list outl ON in_partid=out_partid AND inl.testid=outl.testid
) as tests_passed
INNER JOIN tests ON tests_passed.testid=test
GROUP BY in_partid
编辑:根据OP的评论,我的上述假设是错误的,实际上是一个要求。因此,我认为这是一个满足要求的查询:
SELECT tests_passed.in_partid,SUM(value)
FROM (
SELECT DISTINCT inl.in_partid,IFNULL(last_failed_test,0) as last_failed_test
FROM in_list inl LEFT JOIN (
SELECT in_partid,MAX(inl.testid) as last_failed_test
FROM in_list inl
LEFT JOIN out_list outl ON in_partid=out_partid AND inl.testid=outl.testid
WHERE outl.testid IS NULL
GROUP BY in_partid
) AS last_passed
ON inl.in_partid=last_passed.in_partid
) as tests_passed
INNER JOIN tests ON tests_passed.last_failed_test<test
GROUP BY tests_passed.in_partid
这将返回上面针对所提供的示例数据给出的示例结果。
关于mysql通过比较两个关系来选择行总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9921243/