简体   繁体   中英

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. How would be the query?

Let's suppose I have this 2 tables:

Table 1:

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

Table 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

    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 '

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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