简体   繁体   English

MySQL左联接未按预期工作

[英]MySQL Left Join Not Working As I Expected

Table Name : Feature 表格名称:功能

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

Table Name : property_meta 表名称:property_meta

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

My Query 我的查询

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

Expected Result 预期结果

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

But I am getting without the last row . 但是我没有最后一行 I need that last row also . 我也需要最后一行 How I modify my query to get the last row also? 如何修改查询以获取最后一行?

That means I need to get all rows of Feature table even there is no value in property meta table. 这意味着即使属性元表中没有值,我也需要获取功能表的所有行。

where property_meta.pro_id=300 makes your left join to an inner join . where property_meta.pro_id=300使您的left join成为inner join Add this to the on clause and it is working: 将此添加到on子句中,即可正常工作:

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
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条件限制了结果,而join条件仅连接了表

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

where property_meta.pro_id=300 removes that line, cause this will be null after the unsuccessfull join. where property_meta.pro_id=300删除了该行,因为在不成功的连接之后,该行将为null

remove that condition and you will have 删除该条件,您将拥有

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

Fix accordingly :) 相应地解决:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM