我正在尝试制作一个自动打印订单的系统,但我现在遇到了一个问题。 我正在尝试以打印机可以理解的格式制作一个字符串,现在,我需要在发送之前从数据库中收集数据。现在我的问题是在某些情况下 order_id 是相同的。这是一个例子:
+----------+----------------------+
| order_id | product_name |
+----------+----------------------+
| 1 | Pizza with cheese |
+----------+----------------------+
| 1 | Coca-Cola Zero |
+----------+----------------------+
| 2 | Spaghetti |
+----------+----------------------+
| 3 | Lasagna |
+----------+----------------------+
所以我想做的是将所有“product_name”收集到一个具有相同“order_id”的字符串中,因此它显示为: “芝士披萨,可口可乐零度”
有什么办法吗?
提前致谢。
编辑: 我不知道我是否在上面清楚地提到了它,但我想制作一个显示它的 PHP 脚本。对不起,如果我混淆了。
最佳答案
你可以选择这个
select order_id, count(*), group_concat(product_name)
from orders
group by order_id
having count(*) > 1;
这会为您提供所有具有多个条目的 order_id
,条目数和订单连接在一起。如果您不需要该数字,请在列列表中省略 count(*)
。
如果您想要所有 订单,请省略having
select order_id, count(*), group_concat(product_name)
from orders
group by order_id
并从 PHP 中使用它
$conn = new mysqli($host, $user, $pass, $db);
// use the appropriate select
$result = $conn->query('select order_id, group_concat(product_name) '
. 'from orders group by order_id');
while ($row = $result->fetch_array()) {
// process the result row
}
这当然只是一个简要的概述。您必须添加错误处理并填写您要对结果执行的操作。
关于php - 在 PHP 中显示具有相同 id 的行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13434337/