gpt4 book ai didi

php - 在 mysql (+php) 中检索分组元素的数组

转载 作者:行者123 更新时间:2023-11-29 03:41:30 25 4
gpt4 key购买 nike

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

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

最佳答案

两种基本方法:

  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'];
// ...
}

关于php - 在 mysql (+php) 中检索分组元素的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13332701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com