如何连接父行所有子级的字段?

时间:2019-05-08 12:42:02

标签: mysql sql

我正在构建一个将用于树GUI对象的查询。我有一个具有一对多关系子表的父表。要为树对象创建可用路径,我需要做的是合并父行的所有子代名称。现在,通过当前查询,我每个孩子得到一个结果,但是无论有多少孩子,我都需要一个结果。

查询的问题是行CONCAT(listassets.name, ", ", listprojects.number) AS text。我知道这只会返回一个结果,因为我只有listprojects.nubmer,但是我如何才能得到每个列表项目编号呢?

目前,我得到的是这样的

Asset1, 1234
Asset1, 5478
Asset1, 7893
 其中1234、5478、7893是与该资产关联的项目编号。我想要的是

Asset1 1234. 5478, 7893

这是我的完整查询。作为参考,层次结构是客户具有位置,位置具有区域,区域具有资产,资产具有项目。

SELECT 
CONCAT_WS('/', `listcustomers`.`name`, `listlocations`.`name`, `listareas`.`name`) AS `path`,
CONCAT_WS('/', `listcustomers`.`name`,`listlocations`.`name`, `listareas`.`name`, CONCAT(`listassets`.`name`, ", ", `listprojects`.`number`)) AS `fullPath`,
CONCAT(`listassets`.`name`, ", ", `listprojects`.`number`) AS `text`,
`listassets`.`active` AS `active`,
IF(`listassets`.`active`, 'tree/assetActive.png', 'tree/assetInactive.png') AS `icon`,
IF(`listassets`.`active`, 'tree/assetActive.png', 'tree/assetInactive.png') AS `selectedIcon`,
'color(255,255,255,255)' AS `background`,
'' AS `border`,
'' AS `tootltip`,
'' AS `selectedText`,
'' AS `selectedTooltip`,
'' AS `selectedBorder`,
'color(0,0,0,255)' AS `foreground`,
'color(250,214,138,255)' AS `selectedBackground`,
'color(0,0,0,255)' AS `selectedForeground`,
`listcustomers`.`idx` AS `customerId`,
`listlocations`.`idx` AS `locationId`,
`listareas`.`idx` AS `areaId`,
`listassets`.`idx` AS `assetId`,
NULL AS `projectId`,
NULL AS `projectNum`
FROM
`listassets`
JOIN `listareas` ON `listareas`.`idx` = `listassets`.`parentAreaId`
JOIN `listlocations` ON `listlocations`.`idx` = `listareas`.`parentLocationId`
JOIN `listcustomers` ON `listcustomers`.`idx` = `listlocations`.`parentCustomerId`
JOIN `listprojects` ON `listassets`.`idx` = `listprojects`.`parentAssetId`

我正在使用MySQL 5.6

1 个答案:

答案 0 :(得分:0)

我找到了答案,那就是使用GROUP_CONCAT并按listassets.id分组。