即使mysql表中没有记录,也返回默认数据

时间:2016-05-03 10:07:10

标签: mysql select

使用MySql:

查询结果将在webclient中用于图表

表:tblActivity

+----------------------------------------------------------+
|id |Activityname |state [state is boolean will have 1 or 0] 
+----------------------------------------------------------+
| 1 | activity1   |  1                                     |
| 1 | activity1   |  0                                     |
| 2 | activity2   |  1                                     |        
| 2 | activity2   |  0                                     | 
| 3 | activity3   |  0                                     | 
| 1 | activity1   |  1                                     |
| 2 | activity2   |  0                                     |  
| 4 | activity4   |  1                                     |
+----------------------------------------------------------+

选择查询

 select id, Activityname, state, count(*) as activitycount 
 from tblActivity
 group by id,state

当前输出

 +--------------------------------------+
 |id |Activityname |state |activitycount|
 +--------------------------------------+
 |1  |activity1    | 1    |  2          |
 |1  |activity1    | 0    |  1          | 
 |2  |activity2    | 1    |  1          | 
 |3  |activity2    | 0    |  2          |
 |3  |activity3    | 0    |  1          |
 +--------------------------------------+

预期输出

 +--------------------------------------+
 |id |Activityname |state |activitycount|
 +--------------------------------------+
 |1  |activity1    | 1    |  2          |
 |1  |activity1    | 0    |  1          |
 |2  |activity2    | 1    |  1          | 
 |2  |activity2    | 0    |  2          |
 |3  |activity3    | 1    |  0 [need]   |
 |3  |activity3    | 0    |  1          |
 |4  |activity3    | 1    |  1          |
 |4  |activity3    | 0    |  0 [need]   |
 +--------------------------------------+

所以,即使没有针对特定活动的状态的数据

,我也要返回一行

我尝试过IFNULL,COLEASE等,但找不到最佳解决方案。

1 个答案:

答案 0 :(得分:2)

您需要通过选择所有可用的州/ ID /活动来“创建”派生表,然后将其加入您的查询:

SELECT t2.id,t1.state,t2.activityname,count(s.activityname) as activitycount
FROM (SELECT distinct t.state FROM tblActivity t) t1
CROSS JOIN (select distinct s.id,s.activityname FROM tblActivity s) t2
LEFT OUTER JOIN tblActivity s
 ON(s.state = t1.state and s.activityname = t2.activityname)
GROUP BY t2.id,t1.state,t2.activityname