表名:功能
+--------+----------+
| 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表的所有行,即使属性元表中没有值。
答案 0 :(得分:3)
where property_meta.pro_id=300
使您的left join
成为inner join
。
将其添加到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
答案 1 :(得分: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 :(得分: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
答案 3 :(得分:0)
where property_meta.pro_id=300
删除该行,因为在失败的加入后,这将是null
。
删除该条件,您将拥有
+--------+--------+-------+
| fea_id | pro_id | value |
+--------+--------+-------+
| 1 | 300 | 2500 |
| 2 | 300 | 300 |
| 3 | NULL| NULL |
+--------+--------+-------+
相应修复:)