我有以下表格:
-----------------------------------------
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'].' Advance Amount: '.$row['amount'].'<br />;
echo 'Cheque Num: '.$row['chq_num'].' Cheque Date: '.$row['chq_date']
但是通过上面的提取技术,我只能得到第一个“检查数字”。并且首先检查日期&#39;。如何以某种方式获取,以便我可以获得由&#39;,&#39;分隔的所有支票号和检查日期。 (逗号)?
此致
答案 0 :(得分:2)
您可以使用 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_num
和chq_date
将以逗号分隔的方式返回。
答案 1 :(得分:0)
SELECT advid,
group_concat(chq_num),
sum(amount),
group_concat(chq_date)
FROM my_table
GROUP BY advid
答案 2 :(得分:0)
您可以使用sum
和group_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
请参阅: