2013-02-06 40 views
2

获取COUNT说我有一个表:MySQL的合并,从多个字段

user_id parent_id lev1 lev2 lev3 lev4 
1   0   0  0  0  0 
2   1   1  0  0  0 
3   1   1  0  0  0 
4   2   2  1  0  0 
5   4   4  2  1  0 
6   4   4  2  1  0 
7   5   5  4  2  1 

基本上,这是跟踪父子层次,我想有多少孩子没有父母都有。下面是输出我想:

parent_id  children 
1    5 
2    4 
3    0 
4    3 
5    1 
6    0 
7    0 

我想算合并LEV1,LEV2,LEV3和lev4领域指望有多少ID的所​​有在所有这些领域。

我阅读了关于UNION ALL的内容,但似乎无法弄清楚它是如何运作的。我在想自己加入一个联盟?

+0

不应该parent_id 1返回6? –

+0

@RaphaëlAlthaus你是对的,parent_id 1应该是6.对不起 –

回答

3

对于每个levN列,您需要一个LEFT JOIN针对子查询,该列将返回不同的级别,并为该列计数。然后他们全部加入并加入到user_id

SELECT 
    DISTINCT 
    user_id, 
    /* COALESCE() is needed so NULLs don't ruin the calculation */ 
    COALESCE(l1count, 0) + 
    COALESCE(l2count, 0) + 
    COALESCE(l3count, 0) + 
    COALESCE(l4count, 0) AS children 
FROM 
    yourtable 
    /* a left join individually against each of the `levN` columns to get the count per value of each */ 
    LEFT JOIN (SELECT lev1, COUNT(*) AS l1count FROM yourtable GROUP BY lev1) l1 ON yourtable.user_id = l1.lev1 
    LEFT JOIN (SELECT lev2, COUNT(*) AS l2count FROM yourtable GROUP BY lev2) l2 ON yourtable.user_id = l2.lev2 
    LEFT JOIN (SELECT lev3, COUNT(*) AS l3count FROM yourtable GROUP BY lev3) l3 ON yourtable.user_id = l3.lev3 
    LEFT JOIN (SELECT lev4, COUNT(*) AS l4count FROM yourtable GROUP BY lev4) l4 ON yourtable.user_id = l4.lev4 

http://sqlfiddle.com/#!2/214a8/16

+0

这个伎俩!谢谢@MichaelBerkowski –

2

我可以帮你部分存在,但我并没有显示计数为零东西。 (另外,正如@RaphaëlAlthaus指出的那样,父母1在您的数据中有6位不计数)。

sqlite> .schema 
CREATE TABLE tmp (
user int, 
parent int, 
l1 int, 
l2 int, 
l3 int, 
l4 int 
); 
sqlite> select * from tmp; 
1,0,0,0,0,0 
2,1,1,0,0,0 
3,1,1,0,0,0 
4,2,2,1,0,0 
5,4,4,2,1,0 
6,4,4,2,1,0 
7,5,5,4,2,1 
sqlite> select who,count(who) from 
    ...> (select l1 as who from tmp union all 
    ...> select l2 as who from tmp union all 
    ...> select l3 as who from tmp union all 
    ...> select l4 as who from tmp) 
    ...> where who <> 0 
    ...> group by who; 
1,6 
2,4 
4,3 
5,1 
sqlite> 
+0

嗨,这很好,但我还需要显示与零孩子的父母 –