我想知道是否有人可以帮助我从我的表中选择信息,但是根据订单ID对结果进行分组。我确信这很简单,但我似乎无法使代码正常工作。
这是我的尝试 - 只显示1个结果,而不是6:
SQL:
SELECT *
FROM #__users_orders
WHERE userid = 22
GROUP BY orderid
ORDER BY date DESC
任何帮助将不胜感激:)
编辑:
我想实现这个(或类似的东西)
Array[55542]
(
[0] => stdClass Object
(
[id] => 6
[userid] => 66
[orderid] => 55542
[date] => 2011-08-05 16:30:24
[code] => 121021
[title] => 7 STAR CHICKEN A/KING 71198 1.3KG
[units] => 2
[ctns] =>
)
[1] => stdClass Object
(
[id] => 1
[userid] => 66
[orderid] => 55542
[date] => 2011-08-05 16:06:12
[code] => 302371
[title] => ANCHOVY FILL 730GM
[units] => 2
[ctns] =>
)
[2] => stdClass Object
(
[id] => 6
[userid] => 66
[orderid] => 55542
[date] => 2011-08-05 16:30:24
[code] => 121021
[title] => 7 STAR CHICKEN A/KING 71198 1.3KG
[units] => 2
[ctns] =>
)
[3] => stdClass Object
(
[id] => 1
[userid] => 66
[orderid] => 55542
[date] => 2011-08-05 16:06:12
[code] => 302371
[title] => ANCHOVY FILL 730GM
[units] => 2
[ctns] =>
)
)
Array[55543]
(
[0] => stdClass Object
(
[id] => 6
[userid] => 66
[orderid] => 55543
[date] => 2011-08-05 16:30:24
[code] => 121021
[title] => 7 STAR CHICKEN A/KING 71198 1.3KG
[units] => 2
[ctns] =>
)
[1] => stdClass Object
(
[id] => 1
[userid] => 66
[orderid] => 55543
[date] => 2011-08-05 16:06:12
[code] => 302371
[title] => ANCHOVY FILL 730GM
[units] => 2
[ctns] =>
)
)
答案 0 :(得分:3)
SELECT *
FROM #__users_orders
WHERE userid = 22
ORDER BY orderid DESC
只需选择这样的项目,然后通过迭代结果并为每个新的orderid创建一个新数组,在前端创建对象/数组层次结构。
答案 1 :(得分:1)
您不应在此查询中选择“*”。
按“某些列”分组时。您只能选择“某些列”或some_aggregate_function(其他列)。
e.g。如果您想获得每个订单ID的汇总订单大小和最新日期,您可以执行类似 -
的操作SELECT orderid, sum(ordersize), max(date) FROM #__users_orders WHERE userid = 22 GROUP BY orderid ORDER BY max(date) DESC
答案 2 :(得分:1)
SELECT orderid, COUNT(*)
FROM #__users_orders
WHERE userid = 22
GROUP BY orderid
ORDER BY date DESC
通常,您必须使用聚合(例如COUNT,SUM)和GROUP BY匹配。因此,SELECT中但不在COUNT或SUM中的列位于GROUP BY
中只有MySQL允许您不遵循此规则。其他数据库引擎会出错。
答案 3 :(得分:1)
查询似乎没问题,也许你以错误的方式提取结果
SELECT * FROM table GROUP BY field1;
应返回与
相同的行数SELECT field1,field2 FROM table GROUP BY field1;
但数量不同于
SELECT * FROM table;