Multiple rows to one row query

2019-02-03 20:37发布

问题:

On my database when i do this query:

SELECT *
FROM users u
LEFT JOIN usersToStrategy uts on uts.userID = u.userID
LEFT JOIN strategy s on uts.stratID  = s.stratID  

I get the following results:

 userID    username  fName   utsID  userID   stratID  stratID   stratName
   1       nlubin     Neal    66      1        4       4         s3
   1       nlubin     Neal    65      1        3       3         s5
   1       nlubin     Neal    64      1        2       2         s2
   1       nlubin     Neal    63      1        1       1         s1

How do I structure my query that instead of getting those four rows (for only one user) I get one row for the user with all of the user's strats in one cell in the row like this:

 userID    username  fName      stratNames
   1       nlubin     Neal    s3, s5, s2, s1

I can give you as much information that I can within reason to help with the question.

回答1:

I think you are looking for GROUP_CONCAT

SELECT userID, username, fName, GROUP_CONCAT(stratNames SEPARATOR ', ') AS strats
FROM users u
LEFT JOIN usersToStrategy uts on uts.userID = u.userID
LEFT JOIN strategy s on uts.stratID  = s.stratID  
GROUP BY userID, username, fName


回答2:

You use GROUP_CONCAT.



回答3:

Use GROUP_CONCAT like this

SELECT userID,
username,
fName,   
GROUP_CONCAT(stratNames)
FROM users u
LEFT JOIN usersToStrategy uts on uts.userID = u.userID 
LEFT JOIN strategy s on uts.stratID  = s.stratID   
GROUP BY username;