日期:2014-05-16  浏览次数:20885 次

多表联查,如何保留主表的全部数据,但只插入副表的部分数据?
左表 left_table
id name
1 a
2 b
3 c
4 d
5 e

右表 right_table
id type
1 x
1 y
2 x
2 y
5 x
5 y

我现在要得到下面的结果,怎么写联查语句

id name type
1 a x
2 b x
3 c  
4 d
5 e x

如果我这样写
SELECT * FROM left_table l LEFT JOIN right_table r ON l.id=r.id WHERE r.type = 1
只能得到

id name type
1 a x
2 b x
5 e x

会少了中间的3和4的,怎么办,正确的写法是怎样的?

------解决方案--------------------
SELECT * FROM left_table l LEFT JOIN right_table r ON l.id=r.id and r.type = 1
------解决方案--------------------
SQL code
SELECT * FROM left_table a 
LEFT JOIN right_table b 
ON a.id=b.id and b.type = 1