0

我正在尝试使用 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
4

2 回答 2

1

我会运行一个查询 - 选择所有客户是 bob 并按订单号订购。

然后我会简单地遍历结果并打印 skus。

每当我在迭代中看到新的订单号时,我都会打印格式以开始新订单(并回显其所有元数据,如日期、订单号等)

这是伪代码:

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])
}
于 2013-02-04T23:10:00.513 回答
0

Your table needs something whats called normalization. For example your table is redundant such that you are giving out information about bob 5 times and out of which 2 times you are saying its "sku" is ccc and 2 times saying its bbb. You need to split the tables and normalize it for better performance. Read up on first 3 normal forms believe me it will help you achieve your desired result and will open up flexibility to more complex queries.

于 2013-02-04T23:12:05.803 回答