MYSQL: Convert a list of ids to values in a subquery
mysql, string-interpolation, subquery
Solution
`Normalization` is the best way for this. Otherwise, see `FIND_IN_SET()`
SELECT a.ID,
a.Name,
GROUP_CONCAT(b.Name) Partners
FROM tableName a
LEFT JOIN tableName b
ON FIND_IN_SET(b.id, a.partners)
GROUP BY a.ID, a.Name
- SQLFiddle Demo
Suggested schema:
UserList
- ID (PK)
- Name
- other columns
Partners
- UserID (FK to UserList.ID)
- PartnerID (FK to UserList.ID)
Problem
I'm trying to find a way to make my queries easier to read. Say I have a table: with IDs, names, and partners. Partners is a list of ids. ``` - 0, john, null - 1, mike, "0,2" - 2, sarah, "0,1" ``` Is there a way I can do a subquery to show names instead of the partner ids? select u.id, u.name, (select i.name from users i where i.id in u.parners) from users; Something so I can get results like: ``` - 0, john, null - 1, mike, "john,sarah" - 2, sarah, "john, mike" ``` I've tried something like what I've shown above, but I can't figure out anything special. Any help would be appreciated!