以下代码教我如何按第一列对结果进行分组。但我不知道如何用第二栏做到这一点。请解释并给我一些让我清楚明白的例子。非常感谢。 (抱歉我的英文)
$insert = $dbh->prepare("INSERT INTO fruit(name, colour) VALUES (?, ?)");
$insert->execute(array('apple', 'green'));
$insert->execute(array('pear', 'yellow'));
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Group values by the first column */
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
最重要的是我是否可以根据表字段的名称进行分组。(在这种情况下,我不关心列名的索引,我只知道字段名称)。感谢
答案 0 :(得分:2)
嗯,the manual clearly states:结果按第一个列的值进行分组,所以只需更改:
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
到
$sth = $dbh->prepare("SELECT colour, name FROM fruit");
参见代码示例,您已复制粘贴:
/* Group values by the >> FIRST << column */
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
传递列索引值确实值得一试:
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$byName = $sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
$byColour = $sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP, 1);
答案 1 :(得分:0)
$sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP, columnIndex);
$sth->fetchAll(PDO::FETCH_UNIQUE|PDO::FETCH_GROUP, columnName);
我不知道它是否有效。试试吧。