我正在尝试使用PHP显示按订单号分组的单个客户订单的详细信息。我可以通过运行单独的查询来完成这一基本操作,但这似乎并不有效。有人能帮我找到最有效的方法吗?请参阅以下示例:
我有一个"订单"MySQL表,其结构如下:
|ordernumber|customer|quantity|sku|product |orderdate
-----------------------------------------------------
|1 |bob |2 |aaa|producta|2012-08-30
|1 |bob |1 |bbb|productb|2012-08-30
|1 |bob |4 |ccc|productc|2012-08-30
|2 |jim |10 |aaa|producta|2012-08-30
|2 |jim |1 |ccc|productc|2012-08-30
|3 |bob |1 |bbb|productb|2012-12-15
|3 |bob |4 |ccc|productc|2012-12-15
我想以以下格式输出Bob的订单:
Customer: Bob
Order ID: 1
Order Date: 2012-08-30
Details: *Qty* *Sku* *Product*
2 aaa producta
1 bbb productb
4 ccc productc
____________________________________________________
Customer: Bob
Order ID: 3
Order Date: 2012-12-15
Details: *Qty* *Sku* *Product*
1 bbb productb
4 ccc productc
我将运行一个单一的查询-选择客户为bob的所有查询,并按订单号订购。
然后我会简单地迭代结果并打印sku。
每当我在迭代中看到新的订单号时,我都会打印格式以启动新订单(并回显其所有元数据,如日期、订单号等)
这里是伪代码:
rows = run_sql(select * where customer = bob order by ordernumber asc)
curr_order_id = 0
foreach (row in rows)
{
if (row[order_id] != curr_order_id)
{
curr_order_id = row[order_id]
print(-----------------------)
print(customer : row[customer])
print(order : row[order_id])
print(order date: row[order_date])
print(details: *qty* *sku* *product*)
}
print( row[qty] row[sku] row[product])
}
您的表需要所谓的规范化。例如,您的表是多余的,因此您给出了关于bob 5次的信息,其中2次sku"是ccc,2次说它的bbb。为了获得更好的性能,您需要拆分表并对其进行规范化。阅读前3个普通表单相信我,它将帮助您实现所需的结果,并为更复杂的查询提供灵活性。