mysql - 如何将多个 MySQL 行连接到一个字段中?

标签 mysql sql concat

使用 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        |

但我只想要 concat 行,我有一个 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 函数接受结果集,所以这里有人知道如何做到这一点吗?

最佳答案

测试这个:

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

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

关于mysql - 如何将多个 MySQL 行连接到一个字段中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47927806/

相关文章:

c - 为什么这个串联宏需要一个间接级别?

mysql - 重写 MySQL 的 SQL Server 查询

mysql - Django Web 应用程序的数据库加密,无需在服务器上存储 key

SQL Server - 与 where/on 条件交叉联接

php - 从一个表中选择表行,其中另一个表中表列的值为 x

python - 保留列顺序 - Python Pandas 和列连接

mysql - 优化mysql查询

mysql - 为什么 MySQL 允许 SELECT 查询中的非精确匹配?

sql - Visual Studio 差异窗口 : How to Edit . sql 文件

java - 在 JSF EL 表达式中连接两个字符串