如何LEFT JOIN table1 ON table2 WHERE table2行满足某些条件

时间:2015-07-10 18:19:00

标签: mysql join

请考虑此查询:

SELECT table1.* ,
    (SELECT quantity FROM table2 WHERE id = table1.id AND table2.location = 10) quantity, 
    (SELECT reorder_level FROM table2 WHERE id = table1.id AND table2.location = 10) reorder_level, 
    (SELECT stock_date FROM table2 WHERE id = table1.id AND table2.location = 10) stock_date
FROM table1
WHERE category_id = 5 ORDER BY table1.id;

别名quantitylocationstock_date显然引用table2中符合条件的行:id=table1.idlocation=10

此查询有效,但由于笨拙的子查询,可能不是最理想的。

如何才能最好地将table1加入table2 USING(id),但仅限于location也是10的行。

提示:table1中的一行在table2中有很多行。

不幸的是,实际的表定义要复杂得多,而且我认为将整个事物转储到这个线程上可能会适得其反。

1 个答案:

答案 0 :(得分:1)

您可以在ON()部分中使用其他条件,以便它只会加入符合所提供条件的行

SELECT t1.* ,
t2.quantity ,
t2.reorder_level,
t2.stock_date
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id AND t2.location = 10
WHERE t1.category_id = 5 
ORDER BY t1.id;

另一种方法是使用table2的子选择,只选择位置等于10的行

SELECT t1.* ,
t2.quantity ,
t2.reorder_level,
t2.stock_date
FROM table1 t1
LEFT JOIN 
(SELECT * FROM table2 WHERE t2.location = 10)  t2
 ON t1.id = t2.id 
WHERE t1.category_id = 5 
ORDER BY t1.id;