如何在使用 GROUP BY 时返回数组 [英] How to return array while using GROUP BY

查看:97
本文介绍了如何在使用 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

这很好用,并返回以下数组:

This is working great, and returns the following array:

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,例如:

What I would like to do is to also return all the ID's that match the query from the store_items table, like:

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 的计数,还返回它计数的每一行的 ID.

So, for instance, in the last array element above, instead of just returning a Count of 3, also return the ID's of each row that it counted.

推荐答案

你不能真正得到嵌套的结果,但你可以使用GROUP_CONCAT(DISTINCT store_items.ID ORDER BY ID) AS siIDs获取以逗号分隔的 id 值列表.

You can't really get nested results, but you could use GROUP_CONCAT(DISTINCT store_items.ID ORDER BY ID) AS siIDs to get a comma-separated list of id values.

也可以修改分隔符

http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat

这篇关于如何在使用 GROUP BY 时返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆