2
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) 的用户 1 的所有面板以及用户 1 = 5 的面板总数以及状态 = 0 的用户 1 面板的所有计数,即单个查询中的 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

请建议,谢谢。

4

2 回答 2

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

在这里拉小提琴。

于 2013-10-16T06:09:43.510 回答
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
于 2013-10-16T09:32:04.497 回答