Bharat Paudyal
Bharat Paudyal

Reputation: 124

mysql group by return all the rows

I have two tables (table 1 and table 2). Table 1 consists the options and table 2 consists the result for each options.

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

So when the data is inserted it will be stored in 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. 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.

Upvotes: 1

Views: 25

Answers (1)

forpas
forpas

Reputation: 164089

You can CROSS join table1 to the distinct months of table2 and then LEFT join to table2 to aggregate:

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

Upvotes: 1

Related Questions