2013-03-24 70 views
0

我有2列的用戶名和領導層次化查詢

login_user sponsered_id right_left 
    test1  admin   Right 
    test2  admin   Left 
    test3  test1   Right 
    test4  test1   Left 
    test43  test2   Left 
    test44  test3   Left 

我有一個函數

function display_children($parent, $level) { 

    // retrieve all children of $parent 

    $result = mysql_query('SELECT name, login_user, right_left FROM members_list '. 

          'WHERE sponsered_id="'.$parent.'";'); 


    while ($row = mysql_fetch_array($result)) { 

     // indent and display the title of this child 


    echo '<tr><td>'. 
    $row['login_user'].' </td><td> '.$row['right_left'].' </td><td> '.$row['sponsered_id']. 
    "</td></tr>"; 


     // call this function again to display this 

     // child's children 

     display_children($row['login_user'], $level+1); 

    } 

} 

echo display_children('admin',0); 

,但沒有得到正確的輸出....它給人一種表我輸出

test1 Right admin 
test3 Right test1 
test44 Left test3 
test4 Right test1 
test2 Left admin 
test43 Left test2 

需要輸出

test1 Right admin 
test2 Left admin 

test3 Right test1 
test4 Left test1 

     Right test2 
test43 Left test2 

     Right test3 
test44 Left test3 
+0

你說好好嘗試一下比賽在數據庫中的值輸出: '右test2'多恩斯不存在。我認爲你應該通過login_user來訂購它們,你應該非常接近你所說的輸出。 – Kao 2013-03-24 12:10:31

+0

我想Kao建議,排序你的結果集可能會給你一個更理想的輸出。 此外,我會推薦使用嵌套集模型hierarichal數據,它是更容易使用和遍歷低谷節點和分支在您的層次結構。 – 2013-03-24 12:12:27

+0

@Kao thats wt我的問題是有些值不是在右邊或左邊,它應該顯示空白... – Harinder 2013-03-24 12:21:22

回答

1

試試這個

SELECT 
    login_user, 
    right_left, 
    sponsered_id 
FROM (
    SELECT 
     login_user, 
     right_left, 
     sponsered_id 
    FROM 
     members_list 

    UNION 

    SELECT 
     NULL, 
     CASE when max(right_left) ='Left' THEN 'Right' ELSE 'Left' END AS right_left, 
     sponsered_id 
    FROM 
     members_list 
    GROUP BY 
     sponsered_id 
    HAVING count(sponsered_id) < 2 
) as temp 
ORDER BY 
    sponsered_id, 
    right_left 
+0

thx它的工作......但我可以使用WHERE sponsered_id =與此,因爲我需要輸出根據sponsered_id ?? – Harinder 2013-03-25 03:30:40

+0

@ Harinder,當然,你可以將它添加到最外面的條款中 – Akash 2013-03-25 15:37:36

+0

@Harinder請回答接受 – Akash 2013-04-04 05:09:41

0

,你可以嘗試這個

select login_user , right_left , sponsered_id from (

    select login_user , right_left , sponsered_id 
    from members_list 
    union all 

    select login_user , if(right_left ='left', 'right', 'right') right_left , sponsered_id 
    from members_list 

)t 
    group by sponsered_id, right_left 
    order by login_user 

DEMO HERE

+0

thx for reply ....但它給出錯誤的輸出,因爲你可以看到test2上沒有權利,也沒有權利在測試3但演示是給出了錯誤的輸出;( – Harinder 2013-03-24 14:01:08

+0

錯誤的輸出?很像你的。是test2沒有權利,它沒有顯示正確,它顯示了左邊。我不明白你的意思 – 2013-03-24 14:14:00

+0

如果你看到test43即將到來這是錯誤的,因爲'正確的test2'是空白的,所以它應該顯示空白 – Harinder 2013-03-24 14:21:55