简体   繁体   English

多行到一行查询

[英]Multiple rows to one row query

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.我可以在合理范围内为您提供尽可能多的信息来帮助您解决问题。

You use GROUP_CONCAT .您使用GROUP_CONCAT

I think you are looking for GROUP_CONCAT我认为您正在寻找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

Use GROUP_CONCAT like this像这样使用GROUP_CONCAT

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;

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

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