![](/img/trans.png)
[英]choose the data from the table where COUNT of columns goes from max to min
[英]Table data count max val
我在MySQL中有两个表
+---------+-----------+
| machine | status |
+---------+-----------+
| 40001 | Completed |
| 40001 | Completed |
| 40001 | Completed |
| 40001 | Completed |
| 40001 | Pending |
| 40001 | Pending |
| 40001 | Pending |
| 40001 | Pending |
| 40001 | Pending |
| 40001 | Pending |
+---------+-----------+
And the other one as
+---------+---------+
| machine | packets |
+---------+---------+
| 40001 | 527 |
| 40001 | 1497 |
| 40002 | 1414 |
| 40002 | 2796 |
| 40003 | 392 |
| 40003 | 1663 |
| 40004 | 500 |
| 40004 | 1277 |
+-------+----------+
我想编写一个选择查询,该查询为我提供了该机器的机器,完成计数,未决计数和最大数据包数。 所以我尝试了
SELECT machine,max(packets) AS sync,
sum(if(laststatus='completed', 1, 0)) AS generation,
sum(if(laststatus != 'completed', 1, 0)) AS pending
FROM machine_status
right join machine_packets on machine_packets.machine=machine_status.machine
GROUP BY machine
但是我得到了:
+---------+------+------------+---------+
| machine | sync | generation | pending |
+---------+------+------------+---------+
| 40001 | 1497 | 8 | 2 |
| 40002 | 2796 | 4 | 2 |
| 40003 | 1663 | 6 | 0 |
| 40004 | 1277 | 0 | 2 |
| 40005 | 2755 | 0 | 0 |
| 40006 | 927 | 0 | 0 |
| 40007 | 306 | 0 | 0 |
+---------+------+------------+---------+
如我们所见,值在“生成和待处理”列中加倍。 我哪里做错了 ?
SELECT machine,sync,
sum(if(laststatus='completed', 1, 0)) AS generation,
sum(if(laststatus != 'completed', 1, 0)) AS pending
FROM machine_status
right join (select machine,
max(packets) AS sync
from machine_packets
group by machine) mp on mp.machine=machine_status.machine
GROUP BY machine
它们加倍,因为machine_packets每个ID具有2条记录。 为了避免这种情况,您可以在子查询中移动它
一种安全的方法是使用union all
:
select machine, sum(status = 'completed') then generation,
sum(status <> 'completed') then pending,
max(packets) as packets
from ((select machine, status, 0 as packets
from machine_status
) union all
(select machine, 0, packets
from machine_packets
)
) m
group by machine;
这将在任一表中包括所有计算机的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.