首页 > 解决方案 > 选择 2 列并合并数据

问题描述

我想将 col1 中的相同值与 col2 中的特定数据合并,并将其显示在 html 表中。我的 sql 表看起来像这样

+------+------+
|col1  |col2  |
+------+------+
|1     |test  |
+------+------+
|2     |test1 |
+------+------+
|1     |test2 |
+------+------+
|1     |test4 |
+------+------+
|2     |test8 |
+------+------+

预期结果显示在 html 表格中,如下所示。

+------+------+
|      |test  |
|      |      |
|  1   |test1 |
|      |      |
|      |test2 |
+------+------+
|      |test4 |
|  2   |      |
|      |test8 |
+------+------+

标签: mysqlsqlflaskmariadb

解决方案


您的示例数据不明确,但您可能正在寻找 GROUP_CONCAT:

SELECT 
    col1,
    GROUP_CONCAT(col2 SEPARATOR '\n') col2
FROM mytable 
GROUP BY col1
ORDER BY col1

推荐阅读