繁体   English   中英

如何在1个查询中执行该操作?

[英]How to execute that in 1 query?

我有2表customerorders

客户

| 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  |

仅使用一个查询是否有可能?

您可以简单地在下面进行查询:

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

这里有几个步骤...

首先,您应该运行以下查询:

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

我认为您应该使用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;

尝试通过单个查询来获得期望的结果没有意义。 通过第一个查询获取客户列表。 然后执行第二个查询,这将从第一个查询中为客户加载所有订单。 并循环匹配各个客户的订单。

编辑:像这样

$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;
}

您的SQL SELECT name, age, product, color FROM客户,订单where客户. id =订单.id group by name很好,只需在sql中添加客户ID和订单ID。 然后,在PHP中,当您迭代结果集时,首先将客户信息(id,名称,年龄)填充为客户信息(以id为键,名称(年龄)为值作为数组)。 同样,在键“ orders”中填充该客户的订单,订单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);

尝试这个:

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));

            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM