Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Left Join Subselect

I have a simple table of languages / template id's:

language | template

en, t1
en, t1
au, t2
ge, t3
en, t1
ge, t2
ge, t3

Template is always either t1,t2, or t3. In total there are 3 languages: en, au, ge.

There is lots more information in the table, I am just showing what is relevant to this question, I will be using the data for graphing and so need it returning in this format:

en, t1, 3
en, t2, 0
en, t3, 0
au, t1, 0
au, t2, 1
au, t3, 0
ge, t1, 0
ge, t2, 1
ge, t3, 2

This counts however many template occurrences there are in each language. But, the problem I have is returning a zero count if there are no template id's for that particular language in the table.

I was thinking it would need some sort of left join sub select on the template id to make sure the 3 template id's are returned for each language?

like image 506
StuR Avatar asked Sep 22 '11 19:09

StuR


1 Answers

There might be a better way of doing this, and I haven't tested it in MySQL, but the following works in SQL Server 2005:

Select a.language, b.template, count (c.template) as combo_count
from
(select distinct language from tablename) as a
inner join (select distinct template from tablename) as b on 1 < 2 /* this could be cross join, same thing. */
left outer join tablename c on c.language = a.language and c.template = b.template
group by a.language, b.template
order by 1, 2

Here are the results with your sample data:

au  t1  0
au  t2  1
au  t3  0
en  t1  3
en  t2  0
en  t3  0
ge  t1  0
ge  t2  1
ge  t3  2
like image 158
Joshua Carmody Avatar answered Oct 12 '22 11:10

Joshua Carmody