简体   繁体   English

MySQL左外连接,带有连接表中的Count,显示所有记录

[英]MySQL Left Outer Join with Count from joined table, Show all records

i am trying to create a query where there is a count of related records from another table. 我试图创建一个查询,其中有来自另一个表的相关记录的数量。 I'd like the "parent" records whether there are related records (a count) or not. 我想要“父”记录是否有相关记录(计数)。

SELECT r.region_name, r.region_id, r.abbreviation, r.map_order,
    (IFNULL( COUNT( p.property_id ) , 0 )) AS propertyCount
FROM  `rmp_region` r
LEFT OUTER JOIN  `rmp_property` p 
    ON p.path LIKE CONCAT(  '%/', r.region_id,  '/%' ) 
WHERE p.active =1
AND r.parent_region_id =1
GROUP BY r.region_name, r.region_id, r.abbreviation, r.map_order
ORDER BY r.map_order ASC 

I've tried different variations of this.. but i cannot get the parent records to display if the count is zero/no related records. 我已经尝试过这种方法的其他变体..但是如果计数为零/没有相关记录,我将无法显示父记录。

thanks for any help! 谢谢你的帮助!

You need to move "p.active = 1" from the WHERE clause into the OUTER JOIN criteria. 您需要将“ p.active = 1”从WHERE子句移到OUTER JOIN条件中。

Here's your example with the change: 这是您的更改示例:

SELECT r.region_name, r.region_id, r.abbreviation, r.map_order,
    (IFNULL( COUNT( p.property_id ) , 0 )) AS propertyCount
FROM  `rmp_region` r
LEFT OUTER JOIN  `rmp_property` p 
    ON p.path LIKE CONCAT(  '%/', r.region_id,  '/%' ) and p.active =1
WHERE r.parent_region_id =1
GROUP BY r.region_name, r.region_id, r.abbreviation, r.map_order
ORDER BY r.map_order ASC 

You asked about optimizing it, hoping that a index on the "path" column might help. 您询问如何对其进行优化,希望“路径”列上的索引可能有所帮助。 Unfortunately you are searching for a value of path that matches LIKE CONCAT( '%/', r.region_id, '/%' ) , and no index in the world is smart enough to work with that. 不幸的是,您正在搜索与LIKE CONCAT( '%/', r.region_id, '/%' )匹配的path的值,并且世界上没有任何索引足以与之配合使用。

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

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