如何使用mysql GROUP BY函数获取多条记录

How to use mysql GROUP BY function to get multiple records

我关注table:

-----------------------------------------
id | advid | chq_num | chq_date | amount
-----------------------------------------
 1 | 102 | 121212 | 2015-01-01 | 10000
-----------------------------------------
 2 | 102 | 121213 | 2015-01-02 | 8000
-----------------------------------------
 3 | 103 | 121214 | 2015-01-03 | 9000
-----------------------------------------
 4 | 102 | 121215 | 2015-01-04 | 10000
-----------------------------------------
 5 | 103 | 121216 | 2015-01-05 | 7000
-----------------------------------------

现在我要显示以下信息:

Advance ID: 102  Advance Amount: 28000
Cheque Num: 121212, 121213, 121215 Cheque Date: 2015-01-01, 2015-01-02, 2015-01-04

为此,我使用了以下查询和代码:

SELECT advid, sum(amount), chq_num, chq_date FROM my_table GROUP BY advid

在从 php 执行查询后,同时尝试获取结果:

$row = mysql_fetch_assoc($query);
echo 'Advance ID:'.$row['advid'].'&nbsp;&nbsp;Advance Amount: '.$row['amount'].'<br />;
echo 'Cheque Num: '.$row['chq_num'].'&nbsp;&nbsp;Cheque Date: '.$row['chq_date']

但是通过上面的抓取技巧,我只能得到第一个'Cheque Num'和第一个'Cheque Date'。如何以某种方式获取以便我可以获得所有由“,”(逗号)分隔的检查编号和检查日期?

您可以为此使用group_concat函数

SELECT 
advid, 
sum(amount) as amount, 
group_concat(chq_num) as chq_num, 
group_concat(chq_date) as chq_date
FROM my_table GROUP BY advid

chq_numchq_date 将以逗号分隔返回。

SELECT advid,
       group_concat(chq_num),
       sum(amount),
       group_concat(chq_date) 
FROM my_table 
GROUP BY advid

您可以使用 sumgroup_concat 等聚合函数来获得您想要的结果。

SELECT advid
     , sum(amount) as advance_amount
     , group_concat(chq_num) as cheque_numbers
     , group_concat(chq_date) as cheque_dates
 FROM my_table 
GROUP BY advid

参考

  • MySQL: GROUP_CONCAT
    • 此函数 returns 一个字符串结果,其中包含一组中的串联非 NULL 值。如果没有非 NULL 值,它 returns NULL。