mysql通过键分组返回结果

时间:2012-12-07 05:56:56

标签: mysql sql pdo

我有 league_table

+--------+----------+-------------+
|   id   |   star   |   section   |
+--------+----------+-------------+
|   1    |    1     |      A      |
|   2    |    0     |      A      |
|   3    |    1     |      B      |
|   4    |    1     |      B      |
|   5    |    0     |      C      |
|   6    |    1     |      C      |
|   7    |    0     |      D      |
|   8    |    1     |      D      |
+--------+----------+-------------+

我想知道这是否可能,我可以在小组中返回它们吗?

如果我执行此简单查询SELECT id, star FROM league_table WHERE star = 1",请使用PDO FETCH ALL

我可以输出这个:

Array
(
    [0] => Array
        (
            [id] => 1
            [star] => 1
        )

    [1] => Array
        (
            [id] => 3
            [star] => 1
        )

    [2] => Array
        (
            [id] => 4
            [star] => 1
        )

    [3] => Array
        (
            [id] => 6
            [star] => 1
        )
    [4] => Array
        (
            [id] => 8
            [star] => 1
        )
)

但是,我可以使用此输出以使其更有条理吗?

Array
(
    [A] => Array
        (
            [0] => Array 
                (
                  [id] => 1
                  [star] => 1
                )
        )

    [B] => Array
        (
            [0] => Array
                (
                   [id] => 3
                   [star] => 1
                )
            [1] => Array
                (
                   [id] => 4
                   [star] => 1
        )

    [C] => Array
        (
            [0] => Array 
                (
                  [id] => 6
                  [star] => 1
                )
        )

    [D] => Array
        (
            [0] => Array 
                (
                  [id] => 8
                  [star] => 1
                )
        )
)

3 个答案:

答案 0 :(得分:0)

您必须在代码中将其组织起来。 SELECT id, star, section FROM league_table WHERE star = 1 order by section asc会让你更简单。

如果你正在使用php,它可能看起来像这样

foreach ($result as $key=>$row){
    $output[$row['section']][]=$row;
}

答案 1 :(得分:0)

这是一个简单的解决方案,但不是你需要的

SELECT 
    group_concat(id) as IDs,
    star,
    group_concat(section) as Sections
FROM
     league_table
WHERE star = 1

这将为您提供以下输出

IDs        star    Sections
1,3,4,6,8  1       A,B,B,C,D    

正如您所看到的,ID和Sections具有相同的编号,因此如果将逗号分隔的字段(ID,Sections)转换为数组,则可以使用for循环并访问它们。

答案 2 :(得分:0)

使用可以使用以下SQL。

select group_concat(id), star, section from league_table where star = 1' group by section

//you will get the following result

+--------+----------+-------------+
|   id   |   star   |   section   |
+--------+----------+-------------+
|   1    |    1     |      A      |
|   3,4  |    1     |      B      |
|   6    |    1     |      C      |
|   8    |    1     |      D      |
+--------+----------+-------------+

现在,只要遍历每一行,就可以爆炸(',',id)。 star并不重要,因为所有值都等于1