【发布时间】:2014-09-28 17:35:15
【问题描述】:
edit:似乎在 sqlfiddle 中工作......一定是在其他地方发生错误。谢谢大家。
http://sqlfiddle.com/#!2/f867c/1
我真的被 SQL 中的计数和分组所困扰。
重要的表是transaction_items——如果有人以每辆 100 磅购买 4 辆相同的自行车,那么在transaction_items 中插入四行,每个数量一行(这样做是有原因的,我不想要quantity 列。
我需要做的是从transaction_items 获取所有记录,其中charge_id = '12345' 并按transaction_items.usersid 和transaction_items.item_code 对它们进行分组 - 最终给我一个组列表,每个组与一个唯一用户和独特的产品。因此,如果购物车中有多个产品,则用户可以拥有多个组。如果用户 1 购买了 2 x 商品 1 和 4 x 商品 2,则用户 1 将分为两组,一组用于商品 1,计数为 2,一组用于商品 2,计数为 4。目前,我似乎只能得到一组。
所以如果我在 transaction_items 中有这个:
| id | charge_id | usersid | item_code |
| 1 | 12345 | 12 | 66 |
| 2 | 12345 | 12 | 66 |
| 3 | 66666 | 11 | 66 |
| 4 | 12345 | 12 | 66 |
| 5 | 12345 | 6 | 22 |
| 6 | 77777 | 10 | 66 |
| 7 | 12345 | 12 | 66 |
| 8 | 44444 | 23 | 66 |
| 9 | 12345 | 6 | 22 |
我想先将数据按charge_id AND usersid AND item_code 分组,我想取回这些数据:
Array
(
// The array should contain arrays for each pair of usersid's and item_codes, that all have the same charge_id
[0] => Array
(
//This is a unique group for usersid and item_code
[charge_id] => '12345'
[usersid] => '12'
[item_code] => '66'
[num_of_records] => '4'
)
[1] => Array
(
//This is a unique group for usersid and item_code
[charge_id] => '12345'
[usersid] => '6'
[item_code] => '22'
[num_of_records] => '2'
)
)
所以我希望得到一个数组:
- 将所有具有相同charge_id、userid 和item_code 的记录分组
- 以可用的格式获取数据,并带有计数(就像数量一样)
- 计数(数量)应仅针对每个组,而不是所有记录
我现在得到的似乎只是一个产品 ID、一个用户 ID,而是反映所有用户和项目的记录总数,这与我的目标完全相反! (下面的虚拟输出反映了上面示例表的使用):
Array
(
[0] => Array
(
[charge_id] => '12345'
[usersid] => '12'
[item_code] => '66'
[num_of_records] => '6'
)
)
我现在的查询:
$items = $db->query("
SELECT
count(transaction_items.id) as num_of_records,
transaction_items.*
FROM
transaction_items
WHERE
transaction_items.charge_id = :charge
AND
transaction_items.lmsid = :lmsid
GROUP
BY
transaction_items.usersid,
transaction_items.charge_id,
transaction_items");
我错过了什么?
谢谢!
编辑和更新
这完全取决于 WHERE 子句。当我删除它时,查询可以正常工作,但会从 items 表中收集所有记录,而我只想要 charge_id = '12345' 的那些。因此,我认为这个问题的主题与 GROUP BY 和 WHERE 的组合使用以及为什么我没有得到我期望的结果密切相关。
为了简化问题,现在查询是:
$items = $db->query("SELECT
count(transaction_items.id) as num_of_records,
item_code,
usersid
FROM
transaction_items
WHERE
charge_id = '12345'
GROUP
BY
usersid,
charge_id,
item_code
");
【问题讨论】:
-
transaction_items.*是个坏主意。列出你的字段名称。 -
你说得对,WHERE 子句将其限制为带回一条记录,但如果没有
WHERE charge_id = :charge,我将从 transaction_items 表中获取每条记录 - 我如何将其过滤到特定的charge_id值?我现在已经单独列出了transaction_items.*,我不知道为什么我一开始没有。
标签: mysql sql group-by grouping