由三个元素组成,以显示所有可能的组合

时间:2014-08-13 04:57:37

标签: mysql sql group-by

我有三个表格如下,我尝试按三个元素分组以显示所有可能的组合

Play
--------------------------------
id    typeId    periodId
--------------------------------
1     a       1         
2     b       1         
3     b       1         
4     b       1         
5     a       2         
6     b       1         
7     a       1         
8     b       2         


Period
-------------
periodId
-------------
1
2
3


Type
-------------
typeId
-------------
a
b
c

我尝试了这个但是它不起作用,我看到一些NULL值,但是这个组并没有工作。

SELECT type, p, count(*) as superNiceCount
FROM Play 
RIGHT JOIN Period pp ON Play.periodId = Period.periodId
RIGHT JOIN Type tt ON Play.typeId = Type.typeId
GROUP BY tt.typeId, pp.periodId

预期结果将是

-------------------------
type p  superNiceCount
-------------------------
a   1    2 
a   2    1
a   3    0
b   1    4
b   2    1
b   3    0
c   1    0
c   2    0
c   3    0

我怎么能实现这个目标?

1 个答案:

答案 0 :(得分:1)

看看是否有效

SELECT ty.typeId as type, pe.periodId as p, count(pl.id) as superNiceCount
FROM Period pe 
CROSS JOIN Type ty 
LEFT JOIN Play pl ON (pl.periodId = pe.periodId AND pl.typeId = ty.typeId)
GROUP BY ty.typeId, pe.periodId

如果没有尝试

SELECT ty.typeId as type, pe.periodId as p, count(pl.id) as superNiceCount
FROM (
    SELECT * FROM
    Period pe 
    CROSS JOIN Type ty 
) as t1
LEFT JOIN Play pl ON (pl.periodId = t1.periodId AND pl.typeId = t1.typeId)
GROUP BY ty.typeId, pe.periodId