Mysql选择查询3个表

时间:2018-06-18 07:39:24

标签: mysql sql

我有3张订单,order_option,product_option

顺序

order_id | cus_name | cus_phone
-------------------------------
1        | Test-1   | 9876543211
2        | Test-2   | 9876543212
3        | Test-3   | 9876543213
4        | Test-4   | 9876543214

order_option

product_option_id | order_id 
-------------------------------
11                | 1
12                | 1
13                | 2
14                | 4
15                | 3

product_option

product_id | product_option_id | sku     | qty
------------------------------------------
1          | 11                | TS01    | 3
2          | 12                | TS02    | 2
3          | 13                | TS033   | 3
4          | 14                | TS023   | 3

在这里,我想在order字段中选择product_option表格和sku表格值。

我尝试加入以下查询:

SELECT o.order_id, o.cus_name, o.cus_phone,po.sku,po.qty FROM order o 
LEFT JOIN order_option op 
ON (o.order_id = op.order_id) 
LEFT JOIN product_option po
ON (op.product_option_id = po.product_option_id) 
WHERE po.sku = "TS023"

但它没有显示正确的答案。我不知道我错过了什么。

3 个答案:

答案 0 :(得分:1)

order是一个保留字,使用反引号``。

SELECT o.order_id, o.cus_name, o.cus_phone, po.sku, po.qty 
FROM `order` o 
LEFT JOIN order_option op ON o.order_id = op.order_id
LEFT JOIN product_option po ON op.product_option_id = po.product_option_id
WHERE po.sku = "TS023"

输出:

order_id    cus_name    cus_phone   sku     qty
4           Test-4      9876543214  TS023   3

SQL小提琴:http://sqlfiddle.com/#!9/9b76b/2/0

答案 1 :(得分:1)

将po条件从WHERE移至ON以获得真实LEFT JOIN结果:

SELECT o.order_id, o.cus_name, o.cus_phone,po.sku,po.qty FROM order o 
LEFT JOIN order_option op 
ON (o.order_id = op.order_id) 
LEFT JOIN product_option po
ON (op.product_option_id = po.product_option_id) 
AND po.sku = "TS023"

(在WHERE中,您将获得常规的INNER JOIN结果。)

答案 2 :(得分:0)

@Matt是正确的,这是另一种做法。

SELECT o.order_id, o.cus_name, o.cus_phone, po.sku, po.qty 
FROM `order` o, order_option op, product_option po
WHERE o.order_id = op.order_id
AND op.product_option_id = po.product_option_id
AND po.sku = "TSO23"