简体   繁体   English

显示来自两个联接表的数据时如何更改分组?

[英]How can I change the grouping when displaying data from two joined tables?

I have joined two tables, customers and orders, on the customer id value. 我已经在客户ID值上加入了两个表,客户和订单。 There are multiple entries in orders table with same customer id. 订单表中有多个具有相同客户ID的条目。

When I display the entries of orders table, each order is followed by the customer details. 当我显示订单表的条目时,每个订单后都有客户详细信息。 Instead, I want the customer details to be displayed once followed by all the orders with that customer's id. 相反,我希望一次显示客户详细信息,然后显示具有该客户ID的所有订单。

How do I do that using PHP and MySQL? 我该如何使用PHP和MySQL?

I want the output to be like 我希望输出像

Customer1_name 
Item 1  Quantity
Item 2  Quantity

Customer2_name
Item1  Quantity
Item2  Quantity

But what I'm getting is 但是我得到的是

Customer1_name 
item1 quantity
Customer1_name 
item2 quantity

if he has ordered 2 items 如果他订购了2件物品

In general, like this: 一般来说,像这样:

Execute your query, ordering first by customer ID, then by order ID, (or whatever you want to sort your orders by within each customer section). 执行查询,首先按客户ID排序,然后再按订单ID(或要在每个客户部分中按订单排序的任何内容)进行排序。 It is important to ORDER BY customer_id first ; 它是重要的ORDER BY customer_id 第一 ; if you do not, this method will not work. 如果您不这样做,则此方法将不起作用。

$stmt = $pdo->query('SELECT * FROM customers 
    INNER JOIN orders ON customers.id = orders.customer_id ORDER BY customer_id, order_id');

As you fetch the results, keep track of the customer, and when it changes, output the new customer information and replace the current customer with the new customer. 在获取结果时,请跟踪客户,并在客户发生变化时输出新客户信息,并用新客户替换当前客户。

$customer_id = null;                          // current customer - initialize to null
while ($row = $stmt->fetchObject()) {
    if ($row->customer_id != $customer_id) {
        // customer is different, so start a new customer section
        echo $row->customer_name;
        $customer_id = $row->customer_id;    // reset the current customer
    }
    // always output your order information regardless of whether the customer has changed
    echo $row->order_info;
}

Another approach can be achieved using GROUP_CONCAT() function, you will get customer details only once, and other order details in separate column separated by comma. 使用GROUP_CONCAT()函数可以实现另一种方法,您将仅获得一次客户详细信息,而其他订单详细信息将在单独的列中以逗号分隔。

Considering Your table structure I wrote following query, change the column names as per your requirement. 考虑到您的表结构,我编写了以下查询,请根据您的要求更改列名。

SELECT a.customer_id, a.cust_name, GROUP_CONCAT(b.item_name) FROM customers a 
INNER JOIN orders b ON a.customer_id = b.customer_id
GROUP BY a.customer_id

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

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