0

我有这个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
                )
        )
)
4

3 回答 3

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 的编号相同,因此如果您将逗号分隔的字段(IDs,Sections)转换为数组,则可以使用 for 循环并访问它们。

于 2012-12-07T06:14:39.057 回答
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;
}
于 2012-12-07T06:09:34.787 回答
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      |
+--------+----------+-------------+

现在,您可以在遍历每一行时explode(',', id)。星号并不重要,因为所有值都等于 1

于 2012-12-07T06:26:17.177 回答