How to return array while using GROUP BY

自闭症网瘾萝莉.ら 提交于 2019-12-24 13:39:23

问题


Right now, I have this query:

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 
    )
) 

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 
    )
) 

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.


回答1:


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.

You can also modify the separator

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



来源:https://stackoverflow.com/questions/35234447/how-to-return-array-while-using-group-by

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!