简体   繁体   English

根据另一个表的结果向查询添加行

[英]Adding row to query based on results from another table

Say I have a table called tblUsers with user information and another table called tblBadgesEarned with nm relation to tblUsers containing an entry for every badge earned by a user. 假设我有一个名为tblUsers的表,其中包含用户信息,还有另一个名为tblBadgesEarned的表,与tblUsers的关系为nm,其中包含用户获得的每个徽章的条目。

If I get the a users information from tblUsers I would like the result to include a field called "BadgesEarned" for example that is an array of all the badges earned by said users from tblBadgedEarned. 如果我从tblUsers获得了a用户信息,我希望结果包括一个名为“ BadgesEarned”的字段,例如,该字段是由所述用户从tblBadgedEarned获得的所有徽章的数组。

Is it possible doing this in a single query or do I have to split it up and add the field to the array result afterwards? 是否可以在单个查询中执行此操作,还是我必须将其拆分后再将字段添加到数组结果中?

You can accomplish something like this using GROUP_CONCAT() . 您可以使用GROUP_CONCAT()完成类似的操作。 Here's a sample query based on the minimal schema information you provided: 这是一个基于您提供的最少架构信息的示例查询:

select tblUsers.username, 
  group_concat(distinct tblBadgesEarned.badge_name order by tblBadgesEarned.badge_name)
from tblUsers
  left outer join tblBadgesEarned on tblBadgesEarned.user_id = tblUsers.id 
group by tblUsers.username;

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

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