为了从表中检索一些唯一的数据,我使用以下代码:
$query = $this->Controller->AnotherController->find('all', array('fields' => ['id', 'name', 'email']));
$query->hydrate(false);
$data = $query->distinct()->toArray();
此调用为我提供了以下格式的数据:
[
(int) 0 => [
'id' => '1',
'name' => 'somename',
'email' => 'example@example.com'
],
(int) 1 => [
'id' => '2',
'name' => 'anothername',
'email' => 'anotherexample@example.com'
]
]
我想以这种格式接收此数据:
[
(string) 'id' => ['1', '2'],
(string) 'name' => ['name', 'anothername'],
(string) 'email' => ['example@example.com', 'anotherexample@example.com']
]
是否可以仅使用 SQL 来做到这一点?我的意思是没有后期排序。
最佳答案
类似于 group_concat 的东西就是这里的方法。 https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html
它的基本作用是用分隔符(默认为逗号)连接字段,同时根据特定字段对结果进行分组。在您的情况下,您可以添加一个带有值的伪字段,您可以使用它对整个查询进行分组。
SELECT GROUP_CONCAT(id) as id, GROUP_CONCAT(email) as email, 1 as pseudo_field from yourtable group by pseudo_field;
现在是你的部分了:如果需要的话,你必须找出如何将其很好地实现到你的 PHP 框架模型中;-)
关于php - 如何仅使用 SQL 而不使用 PHP 对唯一数据进行排序(分组)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43149290/