我有2個表customer
和orders
:如何在1個查詢中執行該操作?
客戶:
| custID | Name | Age |
|--------|-------|-----|
| 1 | Peter | 23 |
| 2 | Julie | 34 |
| 3 | Tom | 45 |
訂單:
| custID | product | color |
|--------|---------|-------|
| 1 | shirt | blue |
| 1 | jacket | black |
| 2 | jacket | green |
| 3 | hat | grey |
| 3 | shirt | white |
我現在想獲得的所有客戶和他們的訂單,訂購爲名單。所以,這樣的事情:
Array
(
[0] => Array
(
[ID] => 1
[name] => Peter
[age] => 23
[orders] => Array
(
[0] => Array
(
[product] => shirt
[color] => blue
)
[1] => Array
(
[product] => jacket
[color] => black
)
)
)
[1] => Array
(
[ID] => 2
[name] => Julie
[age] => 34
[orders] => Array
(
[0] => Array
(
[product] => jacket
[color] => green
)
)
)
[2] => Array
(
[ID] => 3
[name] => Tom
[age] => 45
[orders] => Array
(
[0] => Array
(
[product] => hat
[color] => grey
)
[1] => Array
(
[product] => shirt
[color] => white
)
)
)
)
當我這樣做:
SELECT name, age, product, color
FROM `customers`, `orders`
where `customers`.`id` = `orders`.id
group by name
我得到:
| name | age | product | color |
|-------|-----|---------|-------|
| Peter | 23 | jacket | green |
| Julie | 34 | shirt | blue |
| Tom | 45 | hat | grey |
這甚至可能只有一個查詢?
'orders'表除了'custID'還有自己的'id'嗎?看起來你正在加入那個看起來不正確的列。 – dana
@dana:不,沒有額外的列。 – user1170330
由單個查詢產生的任何輸出只能看成表格 - 二維,沒有其他複雜性/分裂。數組內的數組使其在表內的表中使用查詢無法實現。如果你有一個單一的表格結構,可以實現。或者,也許您可以針對每種產品設置客戶名稱和年齡,並讓程序遍歷返回的記錄來檢測客戶ID是否發生更改。 –