如何在查询中对结果进行分组?

时间:2011-09-21 11:01:59

标签: mysql arrays sorting group-by

我有MySQL查询,可以选择用户名和他们的知识(可能不止一个)。

它返回这样的东西......

array(5) {
  [0]=>
  array(5) {
    ["user_id"]=>
    string(2) "30"
    ["name"]=>
    string(6) "foo1"
    ["knowledge"]=>
    string(15) "Basic Materials"
  }
  [1]=>
  array(5) {
    ["user_id"]=>
    string(2) "33"
    ["name"]=>
    string(6) "foo2"
    ["knowledge"]=>
    string(15) "Basic Materials"
  }
  [2]=>
  array(5) {
    ["user_id"]=>
    string(2) "34"
    ["name"]=>
    string(10) "foo3"
    ["knowledge"]=>
    string(9) "Eating"
  }
  [3]=>
  array(5) {
    ["user_id"]=>
    string(2) "34"
    ["name"]=>
    string(10) "foo3"
    ["knowledge"]=>
    string(9) "Financial"
  }
  [4]=>
  array(5) {
    ["user_id"]=>
    string(2) "34"
    ["name"]=>
    string(10) "foo3"
    ["knowledge"]=>
    string(8) "Services"
  }
}

如您所见,在此示例中,它确实返回五个条目。但是,其中三个具有重复的ID(和名称)。我正在寻找一种只返回三个条目的方法......

可以在查询中执行吗?

array(5) {
  [0]=>
  array(5) {
    ["user_id"]=>
    string(2) "30"
    ["name"]=>
    string(6) "foo1"
    ["knowledges"]=>
    array(1) {
        [0] => string(15) "Basic Materials"
    }
  }
  [1]=>
  array(5) {
    ["user_id"]=>
    string(2) "33"
    ["name"]=>
    string(6) "foo2"
    ["knowledges"]=>
    array(1) {
        [0] => string(15) "Basic Materials"
    }
  }
  [2]=>
  array(5) {
    ["user_id"]=>
    string(2) "34"
    ["name"]=>
    string(10) "foo3"
    ["knowledges"]=>
    array(1) {
        [0] => string(15) "Eating"
        [1] => string(15) "Financial"
        [2] => string(15) "Services"
    }
  }
}

我看到的其他选项是在服务器端处理结果。

以下是查询的外观:

SELECT `profiles`.`user_id`, `users`.`name`, `users`.`surname`, `users`.`country`, `profile_knowledges`.`knowledge`
FROM `profiles`
JOIN `users`
ON (`users`.`id` = `profiles`.`user_id`)
JOIN `profile_knowledges`
ON (`profile_knowledges`.`profile_id` = `profiles`.`id`)

1 个答案:

答案 0 :(得分:1)

对于这种特殊情况,你可以这样写:

$users = array();

while ($row = /* fetch a single row from result set */) {
    if (isset($users[$row['user_id']]) == false) {
        $users[$row['user_id']] = array(
            'id' => $row['user_id'],
            'name' => $row['name'],
            'knowledges' => array()
        );
    }

    $users[$row['user_id']]['knowledges'][] = $row['knowledge'];
}

但最好使用ORMDoctrine来处理此类情况。