简体   繁体   中英

MYSQL - Multiple Concantenates in single query

I have a table that includes names and an Id:

Id  surname given
1   John    Doe
2   Fred    Smith
3   James   White
4   Dick    Jones

I have another table that groups these together as Teams:

Team   Mem1  Mem2
A       1     2
B       3     4
C       1     4

Is there a way to Concatenate the names in a single query to get a list of Teams and names?

Result would be:

A   John Doe    Fred Smith
B   James White Dick Jones
C   John Doe    Dick Jones

You can join twice:

select 
    t.id,
    concat(n1.surname, ' ', n1.given) name1,
    concat(n2.surname, ' ', n2.given) name2
from teams t
inner join names n1 on n1.id = t.mem1
inner join names n2 on n2.id = t.mem2

If there are missing names, you can use left join s instead of inner join s.

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