PHP组mysql由两列选择

时间:2014-01-28 08:41:06

标签: php mysql sql group-by

我在MySQL中有这个表:

table

我想按浏览器和版本对选择结果进行分组。

通缉输出:

Array
(
    [firefox 3.0] => 2
    [chrome 24.0] => 1
    [ie 9.0] => 2
    [ie 10.0] => 1
)

问题:如何分组选择以获得想要的输出?

注意:表格可以包含更多版本的浏览器,因此数组会扩展。

我的尝试:

PHP:

public function get_browsers() {
    $query = "
        SELECT browser, COUNT(browser) AS num 
        FROM table
        GROUP BY browser 
        ORDER BY browser ASC
        ";
    $select = mysqli_query($this->c, $query);
    while ($row = mysqli_fetch_array($select)) {
        $data[$row['browser']] = (int) $row['num'];
    }
    return $data;
}

当前输出:

Array
(
    [firefox] => 2
    [chrome] => 1
    [ie] => 3
)

3 个答案:

答案 0 :(得分:3)

public function get_browsers() {
    $query = '
        SELECT   browser, version, COUNT(*) AS num 
        FROM     table
        GROUP BY browser, version
    ';
    $select = mysqli_query($this->c, $query);
    while ($row = mysqli_fetch_array($select)) {
        $data[$row['browser'].' '.$row['version']] = (int) $row['num'];
    }
    return $data;
}

答案 1 :(得分:1)

SELECT concat(browser," ", version) as browser, COUNT(browser) AS num 
        FROM table
        GROUP BY browser, version 
        ORDER BY browser ASC

诀窍是将version添加为组标准;)

答案 2 :(得分:-1)

SELECT browser, CONCAT('browser', 'version') as bv COUNT(browser) AS num 
        FROM table
        GROUP BY bv 
        ORDER BY browser ASC
        ";