我目前正在尝试使用来自两个mysql表“order”和“order_items”的信息创建一个表,因为它们共享订单ID
顺序
ORDER_ITEMS
我想显示一个这样的表,产品名称在同一行,可能需要一个循环
我希望通过内部联接来执行此操作,因为它更适合我正在做什么
这就是我现在所拥有的,但目前无法运作
$query = "SELECT order.date_bought, order.total_price, order_items.product_name FROM order INNER JOIN order_items ON order.order_id = order_items.order_id WHERE order.student_id = $id ORDER BY order_id DESC";
$result = mysql_query($query);
$num = mysql_num_rows($result);
$i=0;
while($i < $num){
$date_bought = mysql_result($result,$i,"date_bought");
echo $date_bought;
}
错误:mysql_num_rows()期望参数1为资源,布尔值为
但我很确定它是因为查询
答案 0 :(得分:2)
order
是一个保留字,逃脱它:
SELECT
o.order_id,
o.date_bought,
o.total_price,
oi.product_name
FROM `order` AS o
INNER JOIN order_items AS oi ON o.order_id = oi.order_id
WHERE o.student_id = $id
ORDER BY o.order_id DESC;
尽量避免使用这些名称。
如果要在每个订单的同一行显示产品名称,请使用GROUP_CONCAT
功能:
SELECT
o.order_id,
o.date_bought,
o.total_price,
GROUP_CONCAT(oi.product_name SEPARATOR ' ') AS ProdcutNames
FROM `order` AS o
INNER JOIN order_items AS oi ON o.order_id = oi.order_id
WHERE o.student_id = $id
GROUP BY o.order_id,
o.date_bought,
o.total_price
ORDER BY o.order_id DESC;
答案 1 :(得分:0)
我认为你是mysql的初学者。试试吧:
SELECT * FROM order o INNER JOIN order_items oi ON o.order_id = oi.order_id WHERE order.student_id = $id GROUP BY o.order_id ORDER BY o.order_id DESC
&#34;组&#34;不要复制结果。