[英]MYSQL Join with Null value returned
I have a query thats joining two table, using the GROUP_CONCAT to get a comma separated list which is then being mapped to an array in an object 我有一个查询,那就是联接两个表,使用GROUP_CONCAT来得到一个逗号分隔的列表,然后将该列表映射到对象中的数组
SQL: SQL:
$sql = "SELECT *,
GROUP_CONCAT(climb_attributes.attribute_id) as climb_attributes
FROM climbs
LEFT JOIN climb_attributes ON
(climbs.id = climb_attributes.climb_id)
GROUP BY climb_id
ORDER BY climbs.id";
PHP PHP
$all_climb_profiles[$climb->id]->attributes = explode(",", $climb->climb_attributes);
Nearly working perfectly, except I currently only get back results IF the climb_attributes table contains the climb id. 几乎可以正常工作,除非我目前仅在climb_attributes表包含爬升ID的情况下才能获得结果。 Essentially a climb can still exist even if it doesn't have any attributes, but at the moment it has to have an attribute to be returned in the results.
本质上,即使没有任何属性,攀爬仍然可以存在,但此刻它必须具有要在结果中返回的属性。
I also need to join it to another table to get the attribute name for the attribute id...if you can help with that as well that would be great, I'm hoping I can figure that out though. 我还需要将其连接到另一个表以获取属性ID的属性名称...如果您也能提供帮助的话,那太好了,我希望可以弄清楚。
First, you should not be using *
to select from all tables when using group by
. 首先,使用
group by
时,您不应使用*
从所有表中进行选择。 You can safely take all the columns from the climb
table. 您可以安全地从
climb
表中取出所有列。
The problem is that you are aggregating on a column in the second table, rather than the first. 问题在于您正在聚集第二个表中的列,而不是第一个表中的列。 And, it is
NULL
if there is no match. 并且,如果没有匹配项,则为
NULL
。 So, a better query is: 因此,更好的查询是:
SELECT c.*, GROUP_CONCAT(ca.attribute_id) as climb_attributes
FROM climbs c LEFT JOIN
climb_attributes ca
ON c.id = ca.climb_id
GROUP BY c.id
ORDER BY c.id;
EDIT: 编辑:
If you want to list the strings, then something like this should work: 如果要列出字符串,则应执行以下操作:
SELECT c.*, GROUP_CONCAT(a.name) as climb_attributes
FROM climbs c LEFT JOIN
climb_attributes ca
ON c.id = ca.climb_id LEFT JOIN
attributes a
ON ca.attribute_id = c.id
GROUP BY c.id
ORDER BY c.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.