r/mysql • u/lungbong • Jan 18 '25
question Can you have a variable amount of columns returned in a SELECT?
I have a table that looks like this:
select * from table;
ID, name
1, Bob
1, Ted
2, Alice
2, Peter
2, Gary
3, George
etc.
I want a query that returns the data in this format:
ID, names
1, Bob, Ted(, NULL)
2, Alice, Peter, Gary
3, George(, NULL, NULL)
etc.
I'd rather not be joining the table to itself as there's no limit on how many rows each ID could have in the tables. Is there a simple way of doing this I'm missing?
1
Upvotes
2
u/Aggressive_Ad_5454 Jan 18 '25 edited Jan 18 '25
You want
As for the order of names on each line, that’s unpredictable unless you say
GROUP_CONCAT(name ORDER BY name)or something similar. GROUP_CONCAT is astoundingly useful and worth learning. https://dev.mysql.com/doc/refman/8.4/en/aggregate-functions.html#function_group-concat5
u/Qualabel Jan 18 '25
Very seriously consider handling issues of data display in application code.