Multiple rows to one row query

2019-02-03 20:57发布

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.

3条回答
ゆ 、 Hurt°
2楼-- · 2019-02-03 21:20

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;
查看更多
放荡不羁爱自由
3楼-- · 2019-02-03 21:25

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
查看更多
Viruses.
4楼-- · 2019-02-03 21:28
登录 后发表回答