2013-02-06 42 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

嗨,這很好,但我還需要顯示與零孩子的父母 –