mysql查询加入group_concat

时间:2013-12-22 23:04:14

标签: php mysql mysqli

我有以下查询,

 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']);
}

我还需要它来从另一个表格username获取rev_users,这怎么可能呢?

1 个答案:

答案 0 :(得分:0)

如果您不希望通过两个查询(或者使用子查询的一个MySQL事务)实现此目的,那么您可以像这样连接:

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函数中使用一个你不知道名字的分隔符。