php - mysql连接三个表和分组

时间:2017-03-25 10:58:48

标签: php mysql loops

我有三张桌子:

产品:

id   name
1    juice
2    chips
3    water

订单:

id   product_id   order_id
1    1            special1
2    3            special1
3    2            special1
4    1            special2
5    2            special2

final_orders:

id   order_id   date
1    special1   25-3-2017
2    special2   25-3-2017

我想使用order_id显示每个订单中的所有产品名称:

ID:Special1
日期:25-3-2017
产品清单:


芯片

ID:Special2
日期:25-3-2017
产品清单:

芯片

我用这个:

$sql = "select * from products,orders where products.id = orders.product_id";

但它不起作用并向我显示重复的结果。

谢谢。

2 个答案:

答案 0 :(得分:0)

如果您想在结果集中看到每条记录的最终订单,那么您必须汇总每个订单中显示的产品。一个选项是以下查询,它使用MySQL的GROUP_CONCAT()

将订单产品聚合为CSV
SELECT t1.order_id,
       t1.date,
       t2.products
FROM final_orders t1
INNER JOIN
(
    SELECT a.order_id, GROUP_CONCAT(b.name) AS products
    FROM orders a
    INNER JOIN products b
        ON a.product_id = b.id
    GROUP BY a.order_id
) t2
    ON t1.order_id = t2.order_id

在这里演示:

Rextester

答案 1 :(得分:0)

您还需要加入final_orders

SELECT *
FROM final_orders AS f
JOIN orders AS o ON f.order_id = o.order_id
JOIN products AS p ON p.id = o.product_id
ORDER BY f.order_id

为防止输出中出现重复,打印输出的循环应仅在final_orders更改时显示信息。见How can i list has same id data with while loop in PHP?