2017-01-31 35 views
1

我有2個表customerorders如何在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 | 

這甚至可能只有一個查詢?

+0

'orders'表除了'custID'還有自己的'id'嗎?看起來你正在加入那個看起來不正確的列。 – dana

+0

@dana:不,沒有額外的列。 – user1170330

+0

由單個查詢產生的任何輸出只能看成表格 - 二維,沒有其他複雜性/分裂。數組內的數組使其在表內的表中使用查詢無法實現。如果你有一個單一的表格結構,可以實現。或者,也許您可​​以針對每種產品設置客戶名稱和年齡,並讓程序遍歷返回的記錄來檢測客戶ID是否發生更改。 –

回答

0

我想你應該用戶INNER JOIN:

SELECT * FROM customers AS c INNER JOIN orders AS o ON c.custID = o.custID GROUP BY c.custID ORDER BY c.custID ASC;

0

有在努力實現與單一的查詢期望的結果是沒有意義的。通過第一個查詢獲取客戶列表。然後執行第二個查詢,該查詢將從第一個查詢中加載客戶的所有訂單。並在一個循環匹配訂單給各自的客戶。

編輯:這樣的事情

$result = []; 
$customers = $pdo->query("SELECT * FROM `customers`")->fetchAll(); 
foreach ($customers as $c) { 
    $result[$c['id']] = $c; 
} 

$orders = $pdo->query("SELECT * FROM `orders` WHERE `custID` IN (".implode(', ', array_keys($result).")"); 
foreach ($orders as $o) { 
    if (!isset($result[$o['custId']]['orders'])) 
    $result[$o['custId']]['orders'] = []; 
    $result[$o['custId']]['orders'][] = $o; 
} 
+1

只做一個查詢的目的是避免各種事務被打開然後關閉。 – Roberto

0

您的SQL SELECT name, age, product, color FROM客戶,訂單where客戶. ID =訂單.id group by name是好的,只是添加客戶ID和訂單ID也在SQL。然後,在PHP中,當您迭代結果集時,首先用客戶ID填充客戶信息(id,name,age)作爲鍵和名稱,將值的年齡視爲數組。同樣,在關鍵'訂單'中爲該客戶填充訂單,其中訂單ID爲關鍵字,值爲數組(產品,顏色)。

一旦你有數組填充,迭代該數組,並繼續把東西放入一個新的數組,因爲你想要的輸出是一個連續鍵(0,1,2等)而不是客戶ID的數組。

$initialList = array(); 
while($row = $result->fetch_assoc()) { 
    if(!array_key_exists($row['customer_id'], $initialList)) { 
     $initialList[$row['customer_id']] = array(
      'name' => $row['name'], 
      'age' => $row['age'], 
      'orders' => array() 
     ); 
    } 
    $initialList[$row['customer_id']]['orders'][] = array(
      'product' => $row['product'], 
      'color' => $row['color'] 
    ); 
} 

$finalList = array(); 
foreach($initialList as $customerId => $customer) { 
    $customer['ID'] = $customerId; 
    $finalList[] = $customer; 
} 

//to print and check the array 
print_r($finalList); 
+0

你能否提供一個PHP部分的例子?我不確定如何鏈接2個查詢。 – user1170330

1

你可以簡單地做下面的查詢:

SELECT * 
FROM customers 
JOIN orders 
USING custID 
GROUP BY Name 
ORDER BY custID ASC; 
+0

我得到這個錯誤:'#1064 - 你的SQL語法有錯誤;請查看與您的MariaDB服務器版本相對應的手冊,以便在'custID GROUP BY名稱 ORDER BY custID ASC LIMIT 0,25'in line 4'處使用正確的語法。 – user1170330

0

試試這個:

SELECT c.custID,c.name, c.age, group_concat(CONCAT_WS(':',o.product,o.color)SEPARATOR ',') as productos 
FROM customers AS c 
INNER JOIN orders AS o ON c.custID = o.custID 
GROUP BY c.custID; 

你只需要解析產品。

$array=array(); 
    while($r = $res->fetch_assoc()) { 
     $id=$row['custID']; 
     $name=$row['name']; 
     $age=$row['age']; 
     $productos=$row['productos']; 
     $productsSeparats = explode(',',$productos); 
     $orders=array(); 
     foreach ($productsSeparats as $value) { 
      $ar=explode(':',$value); 
      array_push($orders, array("product" => $ar[0], "color" => $ar[1])); 
     } 
     array_push($array, array("id" => $id, "name" => $name, "age" => $age, "orders" => $orders)); 

      } 
1

這裏有幾個步驟...

首先,你應該運行下面的查詢:

SELECT 
    `customers`.`id`, 
    `customers`.`name`, 
    `customers`.`age`, 
    `orders`.`product`, 
    `orders`.`color` 
FROM `customers`, `orders` 
where `customers`.`id` = `orders`.`id` 
order by `customers`.`id` 

這應該給你,看起來像這樣反規範化的表格數據:

$array = array(
    array("id" => 1, "name" => "Peter", "age" => 23, "product" => "shirt", "color" => "blue"), 
    array("id" => 1, "name" => "Peter", "age" => 23, "product" => "jacket", "color" => "black"), 
    array("id" => 2, "name" => "Julie", "age" => 34, "product" => "jacket", "color" => "green"), 
    array("id" => 3, "name" => "Tom", "age" => 45, "product" => "hat", "color" => "grey"), 
    array("id" => 3, "name" => "Tom", "age" => 45, "product" => "shirt", "color" => "white") 
); 

然後,您可以轉換數據成您所需的格式如下:

$transformed = array(); 
$i = 0; 
while ($i < count($array)) { 
    $id = $array[$i]["id"]; 
    $name = $array[$i]["name"]; 
    $age = $array[$i]["age"]; 
    $products = array(); 
    while ($i < count($array) && $id == $array[$i]["id"]) { 
     array_push($products, array("product" => $array[$i]["product"], "color" => $array[$i]["color"])); 
     $i++; 
    } 
    array_push($transformed, array("id" => $id, "name" => $name, "age" => $age, "products" => $products)); 
} 

http://sandbox.onlinephpfunctions.com/code/6fe856e1f71f699e84215b6f66d25589f71e255e

相關問題