简体   繁体   English

如何使用 SQL 查询将多列数据放入同一个单元格中?

[英]How to get multiple columns data into the same cell with a SQL query?

I need get an sql result that gets multiple columns data from a table into a single cell for the result.我需要得到一个 sql 结果,该结果将表中的多列数据放入单个单元格中以获得结果。 How would be the query?查询会如何?

Let's suppose I have this 2 tables:假设我有这两张表:

Table 1:表格1:

Name     spec
--------------
James    front
--------------
Henry    front
--------------
Henry    back

Table 2:表 2:

Name     dir
--------------
James    123
--------------
Henry    456

And I want to get this result:我想得到这个结果:

Result Table:结果表:

Name     spec     dir
-----------------------
James    front    123
-----------------------
Henry    front    456
         back
-----------------------

You can try using group_concat() function您可以尝试使用group_concat()函数

    select a.name, group_concat(spec SEPARATOR ' '),dir
    from table1 a inner join table2 b on a.name=b.name
    group by a.name,dir

The Solution for that problem is calling a join.该问题的解决方案是调用连接。 A join combines multiple tables into one using certain identifiers.连接使用某些标识符将多个表合并为一个。 In your problem the identifier is the name.在您的问题中,标识符是名称。 An example solution would be:一个示例解决方案是:

select table1.name, table2.spec, table2.dir
    from table1 inner join table2 on table1.name = table2.name

Example: GROUP_CONCAT is correct, but if you want spec column value print in new line then use ' \\n '示例: GROUP_CONCAT是正确的,但如果您想在新行中打印规范列值,请使用 ' \\n '

SELECT a.name, GROUP_CONCAT(spec SEPARATOR '\n'),dir
FROM table1 a INNER JOIN table2 b ON (a.name=b.name)
GROUP BY a.name,dir;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM