Buildings
并且与Facilities
它们之间的 id 链接表具有多对多关系。我想选择具有特定设施的建筑物,并在单个列中显示每个建筑物的其他设施。
如果我 SELECT 基于 TABLE ,则使用 GROUP_CONCAT 有效Buildings
,
SELECT `b`.`building_name`, `b`.`address`,
GROUP_CONCAT(`ft`.`facility_type` ORDER BY `facility_type`) AS `facilities`
FROM `buildings` `b`
JOIN `buildings_2_facilities` USING (`building_id`)
JOIN `facility_types` `ft` USING (`facility_id`)
WHERE `b`.`latitude` > 1
GROUP BY `building_id`
http://sqlfiddle.com/#!9/ceec20/10
但如果我还基于设施进行选择,则只会在 GROUP_CONCAT 中返回该设施。
SELECT `b`.`building_name`, `b`.`address`,
GROUP_CONCAT(`ft`.`facility_type` ORDER BY `facility_type`) AS `facilities`
FROM `buildings` `b`
JOIN `buildings_2_facilities` USING (`building_id`)
JOIN `facility_types` `ft` USING (`facility_id`)
WHERE `b`.`latitude` > 1 AND `facility_id` = 2
GROUP BY `building_id`
http://sqlfiddle.com/#!9/ceec20/11
如何返回包含每栋大楼所有设施的结果?
http://sqlfiddle.com/#!9/ceec20/13
我们不能在 WHERE 子句中从输出列表中引用别名。要删除记录,
facilities2 IS NULL
我们必须在 HAVING 子句中使用适当的条件:http://sqlfiddle.com/#!9/ceec20/17