php - mysql 连接三个表并分组

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

最终订单:

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

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

ID:特殊1
日期:2017年3月25日
产品列表:
果汁

芯片

ID:特殊2
日期:2017年3月25日
产品列表:
果汁
芯片

我用这个:

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

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

谢谢。

最佳答案

您还需要加入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?

关于php - mysql 连接三个表并分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43015526/

相关文章:

MySQL:如果 t1.row1 = t1.row2 插入 t2

python - 通过迭代创建列表的最快方法

PHP - 用户登录后,重定向到存储在数据库中的地址

mysql - AJAX PHP PDO MYSQL CRUD : tabledata is not showing after adding extra columns

php - 对如何在 php 中读取 curl 返回的 xml 对象感到困惑

mysql - Yii2 - 使用 LONGBLOB 字段创建迁移

list - 当生成的数字在列表中时生成随机数 - ansible

java - 在文件的最后以数字增量保存文件

php - iOS 从 Windows Azure 下载 BLOB

javascript - 使用 JQuery/AJAX/PHP 从另一个 URL 抓取并显示 Web 内容