我在MySQL中有这个表:
我想按浏览器和版本对选择结果进行分组。
通缉输出:
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
)
答案 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
";