2

我需要这个查询的帮助,到目前为止我有这个:

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等于某个值和 order by bdate,我认为我需要用户每次出现的值id bdatedestroyed值,并计算 winner_id 出现的次数,所以结果需要是一个值(winner_id 出现次数的计数)和 3 个数组(discount_id、destroyed、id)。但我不知道如何以我需要的方式检索它。谢谢你的帮助!

4

1 回答 1

0

两种基本方法:

  1. 在 mysql 中聚合并在 php 中“爆炸”
  2. PHP中的聚合

第 1 项涉及在查询中使用一些聚合函数,例如 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']);
  // ...
}

数字 2 是更简单的 SQL,但更丑陋的 PHP。基本上只需选择所有行,然后自己预处理结果。(我推荐以前的解决方案)

foreach($rows as $row) {
  $results_tree[$row['winner_id']]['num_wins']++;
  $results_tree[$row['winner_id']]['discount_ids'][] = $row['discount_id'];
  // ...
}
于 2012-11-11T18:32:29.230 回答