![](/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.