2017-05-26 33 views
0

表名称:功能MySQL的左连接不工作如我所料

+--------+----------+ 
| fea_id | fea_name | 
+--------+----------+ 
|  1 | Price | 
|  2 | Height | 
|  3 | Weight | 
+--------+----------+ 

表名:property_meta

+----+--------+--------+-------+ 
| id | fea_id | pro_id | value | 
+----+--------+--------+-------+ 
| 100 |  1 | 300 | 2500 | 
| 200 |  2 | 300 | 300 | 
| 
+----+--------+--------+-------+ 

我的查询

SELECT * FROM feature LEFT JOIN property_meta ON feature.fea_id = property_meta.fea_id where property_meta.pro_id=300 GROUP by feature.fea_id ORDER BY feature.fea_id ASC

预期结果

+--------+--------+-------+ 
| fea_id | pro_id | value | 
+--------+--------+-------+ 
|  1 | 300 | 2500 | 
|  2 | 300 | 300 | 
|  3 | 300 | NULL | 
+--------+--------+-------+ 

但我得到没有最后一行我需要最后一行也。我如何修改我的查询以获取最后一行?

这意味着即使在属性元表中没有值,我也需要获取Feature表的所有行。

+2

为什么pro_id为300 for fea_id = 3? –

回答

3

where property_meta.pro_id=300使您的left joininner join。 这添加的条款,这是工作:

SELECT * FROM feature LEFT JOIN property_meta ON feature.fea_id = property_meta.fea_id and property_meta.pro_id=300 GROUP by feature.fea_id ORDER BY feature.fea_id ASC 
+0

谢谢。问题解决了。我需要7分钟才能接受答案...... –

+0

@DamithRuwan不客气 – Jens

0

where property_meta.pro_id=300删除这条线,导致这将是null的unsuccessfull后加入。

删除条件,你将有相应

+--------+--------+-------+ 
| fea_id | pro_id | value | 
+--------+--------+-------+ 
|  1 | 300 | 2500 | 
|  2 | 300 | 300 | 
|  3 | NULL| NULL | 
+--------+--------+-------+ 

修复:)

+1

我无法删除pro_id = 300,因为property_meta中有很多pro_id。我只需要获得产品ID 300.例如:产品ID 300的价格。 –

+1

@DamithRuwan它只是一个例子,为什么该行被删除。如Jens所述,将条件添加到“join”而不是“where”。 – dognose

+0

是的,谢谢。我用Jens Answer解决了我的问题。也谢谢你。我不是那个投你的答案的人。 –

2
SELECT * FROM feature LEFT JOIN property_meta ON feature.fea_id = property_meta.fea_id and property_meta.pro_id=300 GROUP by feature.fea_id ORDER BY feature.fea_id ASC 

把where条件为加入条件为where条件限制的结果,唯一的连接条件加入表

+2

请勿仅输入代码。解释你做了什么以及为什么 – Jens

2
SELECT * FROM feature LEFT JOIN property_meta 

ON feature.fea_id = property_meta.fea_id 
    AND property_meta.pro_id=300 -- <-- need to move this condition here or the where clause will remove the last row 

GROUP by feature.fea_id ORDER BY feature.fea_id ASC