如何使用GROUP BY时返回数组
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用GROUP BY时返回数组相关的知识,希望对你有一定的参考价值。
现在,我有这个查询:
SELECT COUNT(*) AS Count, SUM(Ask) AS Ask, SUM(Cost) AS Cost, Provider, Factura FROM store_items
WHERE (
Provider NOT IN(SELECT Provider FROM store_provider_invoices)
AND Factura NOT IN(SELECT Factura FROM store_provider_invoices)
)
OR Factura NOT IN(SELECT Factura FROM store_provider_invoices)
GROUP BY Provider, Factura
这很好用,并返回以下数组:
Array (
[0] => Array (
[Count] => 1
[ID] => 13
[Ask] => 20.00
[Cost] => 10.00
[Provider] => 5
[Factura] => 8
)
[1] => Array (
[Count] => 1
[ID] => 18
[Ask] => 125.01
[Cost] => 110.01
[Provider] => 5
[Factura] => 34
)
[3] => Array (
[Count] => 3
[ID] => 14
[Ask] => 210.00
[Cost] => 150.00
[Provider] => 6
[Factura] => 5
)
)
我还想从store_items
表中返回与查询匹配的所有ID,例如:
Array (
[0] => Array (
[ID] => Array (
[0] => 101
)
[Count] => 1
[Ask] => 20.00
[Cost] => 10.00
[Provider] => 5
[Factura] => 8
)
[1] => Array (
[ID] => Array (
[0] => 102
)
[Count] => 1
[Ask] => 125.01
[Cost] => 110.01
[Provider] => 5
[Factura] => 34
)
[3] => Array (
[ID] => Array (
[0] => 103
[1] => 104
[2] => 105
)
[Count] => 3
[Ask] => 210.00
[Cost] => 150.00
[Provider] => 6
[Factura] => 5
)
)
因此,例如,在上面的最后一个数组元素中,不仅返回3的Count,还返回其计数的每一行的ID。
答案
您无法真正获得嵌套结果,但可以使用GROUP_CONCAT(DISTINCT store_items.ID ORDER BY ID) AS siIDs
获取ID值的逗号分隔列表。
以上是关于如何使用GROUP BY时返回数组的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 LINQ group by 子句返回唯一的员工行?
如何使用 where 和 Group by 返回多个总和结果