Mysql JOIN没有为连接表返回值

时间:2013-02-10 07:01:04

标签: php mysql left-join

我无法为我的生活弄清楚为什么我无法从表B中获取图像。它从表A中返回来自表A中的所有内容。

我想知道它是否是表结构。表的设置方式是order_detail表中可能有多个order_number实例。 Product_id字段都是INT(10),之前order_detail表没有主键(自动增量)。由于订单号是从另一个表中获取的,并且每个订单对于购买的每个产品都可以有10个相同的订单号,因此主键是一个单独的字段。

我应该将order_number创建为索引字段吗?任何帮助都很棒b / c我即将放弃。

Here is order details:
id      order_number  date_time         product_id  product_name    quantity
2       10011     2012-12-20 14:11:24   13          T-Shirt         1
3       10011     2012-12-20 20:02:31   11          T-Shirt         1

Here is products:
product_id  who product_name    color   size    price   image
13          men T-shirt     red medium  15.00   /images/apparel/t-shirt.jpg
11          men T-Shirt         red small   15.00   /images/apparel/t-shirt.jpg

This is the end result of my query:

Order Number    Image   Product Name    Quantity    Cost Each   Total
10011               T-Shirt         2           $15.00          $30
10011               T-Shirt         2           $15.00      $30




$order_number = $_GET['var1'];
$query = "SELECT a.product_name, a.quantity, b.image, a.product_cost FROM order_detail a LEFT JOIN products b ON a.product_id = b.product_id WHERE a.order_number = '$order_number'";
$data = mysqli_query($dbc, $query); 

while($row = mysqli_fetch_assoc($data)){
$prod_name = $row['product_name'];
$quantity = $row['quantity'];
$cost = $row['product_cost'];
$img = $row['image'];

1 个答案:

答案 0 :(得分:3)

它可以处理您的数据和查询并进行一些更改(order_detail表中没有product_cost字段):
http://www.sqlfiddle.com/#!2/38c9b/7