简体   繁体   English

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

[英]Return default data even if no record in mysql table

Using MySql: 使用MySql:

The query results will be used at webclient for chart 查询结果将在WebClient上用于图表

Table: tblActivity 表: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 Query 选择查询

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

Current Output 电流输出

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

Expected Output 预期产量

 +--------------------------------------+
 |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]   |
 +--------------------------------------+

so, I want to return a row even though there is no data for attribute state for particular activity 因此,即使没有特定活动的属性状态数据,我也想返回一行

I tried with IFNULL, COLEASE etc. but cannot find optimum solution. 我尝试使用IFNULL,COLEASE等,但是找不到最佳解决方案。

You need to 'create' a derived table by selecting all the states/id/activity available and left join it to your query: 您需要通过选择所有可用的状态/标识/活动来“创建”派生表,并将其加入查询中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM