简体   繁体   English

mysql group by 返回所有行

[英]mysql group by return all the rows

I have two tables (table 1 and table 2).我有两个表(表 1 和表 2)。 Table 1 consists the options and table 2 consists the result for each options.表 1 包含选项,表 2 包含每个选项的结果。

 **table1**                    table2
 id                            id
 optionvalue                   optionvalueid
                               time (unixtime)

So when the data is inserted it will be stored in table2.因此,当插入数据时,它将存储在 table2 中。 There are 5 optionvalue in table 1 and when data is inserted, then in the table2 it will insert the optionvalueid of table 1 and timestamp in unixtimestamp.表1中有5个optionvalue,插入数据时,table2会插入表1的optionvalueid和unixtimestamp中的timestamp。 Eaach month, I want to count the number of values for each optionvalue.每个月,我想计算每个选项值的值的数量。 Evene if there is no value for an optionvalue, I still want to see count as zero.即使选项值没有价值,我仍然希望将计数视为零。

I did the following query but only return the value with rows with data only.我做了以下查询,但只返回带有数据的行的值。

 SELECT 
po.id,po.optionvalue, COUNT(pr.optionvalueid) as votes,  
FROM_UNIXTIME(`time`, '%m-%Y') as ndate
FROM table 1 
LEFT JOIN table 2 pr ON po.id=pr.optionvalueid 
GROUP BY ndate, po.optionvalue ORDER BY ndate ASC

Is there any other ways to make the query so that it will return all the options even if there is no value.是否有任何其他方法可以进行查询,以便即使没有值也会返回所有选项。

You can CROSS join table1 to the distinct months of table2 and then LEFT join to table2 to aggregate:您可以将table1 CROSS连接到table2的不同月份,然后LEFT连接到table2以进行聚合:

SELECT t.ndate, t1.id, t1.optionvalue, COUNT(t2.optionvalueid) votes  
FROM table1 t1 
CROSS JOIN (SELECT DISTINCT FROM_UNIXTIME(`time`, '%m-%Y') ndate FROM table2) t 
LEFT JOIN table2 t2 ON t1.id = t2.optionvalueid AND t.ndate = FROM_UNIXTIME(t2.`time`, '%m-%Y') 
GROUP BY t.ndate, t1.id, t1.optionvalue 
ORDER BY t.ndate ASC

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

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