我需要一些关于这个查询的帮助,到目前为止我有这个:
SELECT * FROM coupons WHERE discount_id = '1' AND client_username = 'Zara' GROUP BY winner_id桌子是这样的
id client_username winner_id bdate discount_id destroyed
72 zara 1125405534 2012-11-11 03:34:49 4 0
71 zara 1125405534 2012-11-11 03:34:43 1 0
70 zara 1125405534 2012-11-11 03:34:27 1 0我想按winner_id (它是唯一的用户id)对结果进行分组,其中discount_id等于某个值并按bdate排序,我认为我需要用户每次出现的id bdate和destroyed值,还需要计算winner_id出现的次数,因此结果需要是一个值( winner_id出现的次数)和3个数组(discount_id,destroyed,id)。但我不知道如何以我需要的方式检索它。谢谢你的帮助!
发布于 2012-11-12 02:32:29
两种基本方法:
mysql中的
中的“分解”PHP中的
第一个涉及在查询中使用一些聚合函数,比如COUNT()和GROUP_CONCAT():
SELECT count(*) as num_wins, GROUP_CONCAT(discount_id, ',') as discount_ids ...然后,在PHP中,这些GROUP_CONCAT列可以在循环结果时被“分解”成数组:
foreach($rows as $row) {
$discount_ids = explode(',', $row['discount_ids']);
// ...
}第二个是更简单的SQL,但是更丑陋的PHP。基本上只需选择所有行,然后自己对结果进行预处理。(我推荐以前的解决方案)
foreach($rows as $row) {
$results_tree[$row['winner_id']]['num_wins']++;
$results_tree[$row['winner_id']]['discount_ids'][] = $row['discount_id'];
// ...
}https://stackoverflow.com/questions/13332701
复制相似问题