简体   繁体   中英

MySQL query - single row in one table with multiple rows in another table

I have the following data model

Table: User
USER ID
USER NAME

Table: Group
GROUP ID
GROUP NAME

Table: User Group
GROUP ID
USER ID

I am trying to display a screen with all group names and associated users - the front end is PHP

The query I have is as below -

`SELECT a.group_id,
        a.group_name,
        GROUP_CONCAT(g.user_id) AS user_ids,
        GROUP_CONCAT(u.user_fname) AS user_names
 FROM   group a, user_group g, user u
 WHERE  a.group_id = g.group_id
 AND    g.user_id = u.user_id
 GROUP BY a.group_id`

My question : As you can see from the above query - I have to have two lists of concatenated strings that represent user ids and user names. This becomes a headache in PHP as I have to 1. Explode both concatenated strings into arrays 2. Run a loop through both arrays and construct User objects from them 3. Then pass the array of objects over

Is there a more efficient / better way to do this? Any suggestions, pointers would be appreciated.

Do you want just one list?

SELECT g.group_id, g.group_name,
       GROUP_CONCAT(g.user_id, ':', u.user_fname) AS names_and_ids
FROM group g join
     user_group ug
     on g.group_id = ug.group_id join
     user u
     on ug.user_id = u.user_id
GROUP BY g.group_id, g.group_name;

Notice the following changes:

  • I added a group by so you get one row per group.
  • I changed the aliases to be abbreviations for the table names, so the query is easier to read.
  • I modified the group_concat() to include both the user id and user name in one list.
  • I changed the join to use explicit join syntax instead of implicit joins in the where clause.

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