2013-12-22 169 views
0

我有以下查詢,MySQL查詢加入GROUP_CONCAT

SELECT 
    p.id AS parent, GROUP_CONCAT(c.id) AS children 
FROM 
    rev_r_clients AS p 
JOIN 
    rev_r_clients AS c ON c.parent_client_id = p.id 
GROUP BY 
    p.id 

它得到id爲家長和家長的孩子。從那以後,我送的映射id使用以下功能陣列,

$parents = Array(); 

while ($row = $res->fetch_assoc()) { 
    $parents[$row['parent']] = explode(',',$row['children']); 
} 

我需要它從另一個表獲得usernamerev_users)爲好,怎麼能這樣做?

+0

添加到加入rev_users – Mihai

回答

0

如果你不想與兩個查詢(或者使用子查詢或者一個MySQL的交易),以實現這一目標,那麼你可以Concat的是這樣的:

SELECT 
    p.id AS parent_id, p_u.name, GROUP_CONCAT(CONCAT(c.id, '-', c_u.name)) AS children 
FROM 
    rev_r_clients AS p 
JOIN 
    rev_r_clients AS c ON c.parent_client_id = p.id 
JOIN 
    rev_users c_u ON c_u.id= c.id 
JOIN 
    rev_users p_u ON p.id = p_u.id 
GROUP BY 
    p.id 

不過要小心這樣做。 GROUP_CONCAT可以獲得多大的限制。查看文檔http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

而且你的代碼看起來像

$parents = Array(); 
while($row = $res->fetch_assoc()) { 
    $children = explode(',',$row['children']); 
    foreach($children as $child){ 
    $child_info = explode('-', $child); 
    if(!isset($parents[$row['parent_id']])){ 
     $parents[$row['parent']] = array(
     'id' => $row['parent'], 
     'name' => $row['name'], 
     'children' => array() 
    ) 
    } 
    $parents[$row['parent']]['children'][] = array(
     'id' => $child_info[0], 
     'name' => $child_info[1] 
    ); 
    } 
} 

最後要小心使用你的CONCAT功能的分離,你知道會不會是在名稱中。

+0

這是非常有益的,謝謝,但現在我怎麼能打印childs和父母id的名稱? 老例子我能做到這與遞歸函數一樣, 功能子樹($ ID,$父母){ 回聲「​​客戶端編號:​​ ';echo $id;echo '」; ($ child,$ parents); if(isset($ parents [$ id])) foreach($ parents [$ id] as $ child) { subtree($ child,$ parents); } } – user3117183

+0

不確定是什麼問題?查詢是否不返回您需要的數據?或者你想知道如何輸出這個新的數據結構? – user2923779

+0

是如何輸出新結構 – user3117183