MySQL Left Join Subselect

时间:2011-09-22 19:37:32

标签: mysql left-join subquery

我有一个简单的语言/模板ID表:

语言|模板

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

模板始终为t1,t2或t3。总共有3种语言:en,au,ge。

表格中有更多信息,我只是展示与此问题相关的内容,我将使用数据进行绘图,因此需要以这种格式返回:

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

这会计算每种语言中出现的模板数量。但是,如果表中没有该特定语言的模板ID,我遇到的问题是返回零计数。

我认为在模板ID上需要某种左连接子选择以确保为每种语言返回3个模板ID?

3 个答案:

答案 0 :(得分:6)

可能有一种更好的方法可以做到这一点,我还没有在MySQL中测试它,但以下在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

以下是您的示例数据的结果:

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

答案 1 :(得分:0)

  Select a.language, a.template, Count(*) count
  From (Select Distinct language, template From table) a
     Left Join table b
         On b.language = a.language
             And b.template = b.template
  Group By a.language, a.template

答案 2 :(得分:0)

您需要的是两个列出语言和模板可能值的表。

CREATE TABLE language (...) AS SELECT DISTINCT language FROM your_table;
CREATE TABLE template (...) AS SELECT DISTINCT template FROM your_table;

然后你可以这样做:

SELECT l.language, t.template, SUM(CASE WHEN yours.language IS NULL THEN 0 ELSE 1 END) count
FROM language l CROSS JOIN template t
LEFT OUTER JOIN your_table yours ON l.language = yours.language AND t.template = yours.template
GROUP BY l.language, t.template;