从MySQL数据库构造select语句

时间:2012-10-31 23:39:17

标签: php mysql

我正在使用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。

1 个答案:

答案 0 :(得分: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

由于对订单详细信息进行分组,每个细节会列出一行......