简体   繁体   中英

Joining two tables and display second table row data comma seperated for first table rows using single query

I need to output row data from a table while joining with another table and column data in second table should be comma seperated for each first table row by a single query. If there is no matching rows in second table, It should not in output. Following are the tables.

users table
╔══════════╦═════════════════╗
║ user_id  ║    username     ║
╠══════════╬═════════════════╣
║ 1        ║ abc             ║
║ 2        ║ def             ║
║ 3        ║ ghi             ║
║ 4        ║ jkl             ║
╚══════════╩═════════════════╝

users_friends table
╔══════════╦═════════════════╗
║ user_id  ║    friend_id    ║
╠══════════╬═════════════════╣
║ 1        ║ 1               ║
║ 1        ║ 2               ║
║ 1        ║ 3               ║
║ 2        ║ 1               ║
║ 2        ║ 3               ║
║ 3        ║ 4               ║
╚══════════╩═════════════════╝

I want the output is as follows.

╔══════════╦═════════════════╗═════════════════╗
║ user_id  ║    user_name    ║       friends   ║
╠══════════╬═════════════════╣═════════════════╣
║ 1        ║ abc             ║  1,2,3          ║
║ 2        ║ def             ║  1,3            ║
║ 3        ║ ghi             ║  4              ║
╚══════════╩═════════════════╝═════════════════╝

I tried query as follows. But it repeat data. But It is not working.

$sql= "SELECT user_id, user_name, friend_id FROM users INNER JOIN users_friends ON users.user_id= friends.user_id"

Use the MySQL GROUP_CONCAT() function:

SELECT u.user_id, u.user_name, GROUP_CONCAT(uf.friend_id)
FROM users u INNER JOIN users_friends uf ON u.user_id = uf.user_id
GROUP BY user_id, user_name

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