0

我有 4 张桌子用来尝试获取客户订单:

account
- account_id
- username

product
- product_number
- product_name

customer_order
- customer_order_id
- fk_account_id (foreign key)

customer_order_details
- fk_customer_order_id (foreign key)
- fk_product_id (foreign key)    

这是我的查询......这有点令人困惑,但是:

SELECT customer_order_details.fk_customer_order_id, product.product_name,
customer_order_details.colour, customer_order_details.size
FROM customer_order, customer_order_details, product, account
WHERE customer_order.customer_order_id = 
customer_order_details.fk_customer_order_id
AND customer_order_details.fk_product_id = product.product_id
AND customer_order.fk_account_id = account.account_id
AND account.username = 'user1'
GROUP BY customer_order_details.fk_customer_order_id;

它应该按 customer_order_details 表中的外键 (fk_customer_order_id) 分组。我想要的结果是这样的:

1
Microfleece Vest
Jacket With Hood

2
Jacket With Hood

相反,我得到类似的东西:

1
Microfleece Vest

2
Jacket With Hood

我的 PHP 代码只是通过一个 while 循环运行并打印出 product_name 和 fk_customer_order_id。

4

1 回答 1

0

下面是一个 JOIN 语法的例子:

 SELECT d.fk_customer_order_id, p.product_name, d.colour, d.size
 FROM customer_order AS o
 LEFT JOIN customer_order_details AS d ON o.customer_order_id = d.fk_customer_order_id
 LEFT JOIN product AS p ON d.fk_product_id = p.product_id
 LEFT JOIN account as a ON o.fk_account_id = a.account_id
 WHERE a.username = 'user1'
 GROUP BY d.fk_customer_order_id
 ORDER BY d.fk_customer_order_id;

请尝试上述方法。我使用表别名使它更容易阅读。为了加快查询速度,请确保为所有关系键设置了索引。

但是,您的输出将是:

1 Microfleece Vest
1 Jacket With Hood
2 Jacket With Hood

由于对订单详细信息进行分组将在每个详细信息中列出一行...

于 2012-10-31T23:55:46.930 回答