table:panel
id PanelName email_id status
1 A 1 0
2 B 1 1
3 C 1 0
4 D 1 1
5 E 1 1
-------------------------
6 A1 2 0
7 B1 2 1
8 C1 2 0
-------------------------
9 D1 3 1
10 E1 3 1
我需要状态为1(B,D,E
)的user1的所有面板
以及用户1的面板总数= 5以及用户1的面板的所有计数状态= 0,即单个查询中的2。
select p.*,Count(p1.id) as totalPanels
from panel p
INNER join panel p1 on (p.email_id=p1.email_id)
where p.email_id=1 and p.status =1
Group by p.id
这给了我所有面板的状态1和总面板数。但是如何在同一个查询中统计状态为0的面板?
Expected output will be:
id |PanelName| email_id |status| TotalPanel| Rejectedpanel
1 A 1 0 5 2
2 B 1 1 5 2
3 C 1 0 5 2
4 D 1 1 5 2
5 E 1 1 5 2
另一个原因是子查询如下,但我不必使用
select p.id,Count(p1.id) as totalPanels,
(select count(id) from panel p2 where p2.status=0 and p2.email_id=p.email_id ) as RejectePanel
from panel p
INNER join panel p1 on (p.email_id=p1.email_id)
where p.email_id=1
Group by p.id
请建议,谢谢。
答案 0 :(得分:2)
好吧,我完全会选择2个不同的查询,但这里是符合您预期输出的混合内容:
SELECT p1.*,
(SELECT count(*) FROM panel p2
WHERE p1.email_id = p2.email_id) TotalPanel,
(SELECT sum(status = 0) FROM panel p2
WHERE p1.email_id = p2.email_id) RejectedPanel
FROM panel p1
WHERE p1.email_id = 1
小提琴here。
答案 1 :(得分:0)
不确定为什么你不能使用子查询,尽管我通常会避免使用核心子查询。
你可以试试这样的事情
SELECT p.*, TotalPanel, AcceptedPanel, RejectedPanel
FROM panel p
INNER JOIN
(
SELECT email_id, COUNT(*) AS TotalPanel, SUM(IF(status = 1, 1, 0)) AS AcceptedPanel, SUM(IF(status = 0, 1, 0)) AS RejectedPanel
FROM panel
GROUP BY email_id
) Sub1
ON p.email_id = Sub1.email_id
WHERE p.email_id = 1