如何将多个MySQL行连接成一个字段?

3
使用 MySQL,我可以做如下操作:
SELECT c.id_category, c.id_category_type, c.label, c.id_parent
FROM category c
WHERE  c.id_category_type < 3 
ORDER BY c.id_category_type;

结果是:
id_category |id_category_type |label                 |id_parent |
------------|-----------------|----------------------|----------|
1           |1                |Demande d'information |-1        |
2           |1                |Réclamation           |-1        |
18          |1                |TEST                  |-1        |
3           |2                |Autre                 |1         |
4           |2                |Mairie                |1         |
5           |2                |Stationnement         |1         |
6           |2                |Autre                 |2         |
7           |2                |Familles              |2         |
19          |2                |TESTDOMAINE           |18        |

但我只想要将具有id_categoryid_parent的行进行合并。

示例:

Autre-Demande d'information
Mairie-Demande d'information
Stationnement-Demande d'information
Autre-Réclamation
Familles-Réclamation
TESTDOMAINE-TEST

我在MySQL Doc上查找函数,看起来CONCATCONCAT_WS函数没有接受结果集的选项,那么这里有谁知道如何做到这一点吗?

1个回答

3

测试一下:

SELECT category.id_category, category.id_category_type, 
CONCAT(category.label, '-', parents.label), category.id_parent  FROM category INNER JOIN
(SELECT id_category AS id, label FROM category WHERE id_parent = -1) AS parents
ON parents.id = category.id_parent WHERE  category.id_category_type < 3 
ORDER BY category.id_category_type;

你的数据混合了“父行”和“子行”:当一个记录具有id_parent = -1时,我认为它是一个父行,当id_parent <> -1时则为子行。
你正在请求一个结果列,该列将“子行”和“父行”的“标签”列连接在一起,因此需要构建一个“父表”,可以通过以下方式实现:
(SELECT id_category AS id, label FROM category WHERE id_parent = -1) AS parent

然后,您可以像使用任何其他表格一样使用“parent”表格并构建您的连接查询。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接