I currently have a hard coded view with the following sql:
select username
,(case user_role.role_id when 1 then true else false end) as ROLE_SUPER
,(case user_role.role_id when 2 then true else false end) as ROLE_ADMIN
,(case user_role.role_id when 3 then true else false end) as ROLE_VIEW
,(case user_role.role_id when 4 then true else false end) as ROLE_USER
,(case user_role.role_id when 5 then true else false end) as ROLE_EMAIL
from user
left outer join user_role on user.id=user_role.user_id
left outer join role on user_role.role_id = role.id;
my question is whether or not it is possible to dynamically generate role columns from the records in the role table.
You can do what you want to do, but I am not sure why you would want to. Once you have your dynamic column aliases, how do you plan on referencing them? That is, if you pull your column aliases from the database, how will you then be able to use them? I may be missing the reason behind your question.
Anyway, I assume you have a structure like this:
From that, you can obtain information about users and their role(s):
You can also create a column alias for a specific role:
However, if I understand your question correctly, what you want to do is to generate the column alias from the role name. You cannot use a variable as a column alias in a MySQL statement, but you can construct a prepared statement:
As you will see from the output, that generates a string which contains a SQL SELECT statement. You now need to create a prepared statement from that string, and execute the result:
EDIT
To make calling the crosstab query easier, you could wrap the whole thing up in a stored procedure. In the following example, I could not get the
GROUP_CONCATto work within theSET @sqlstatement, as it does above. Instead, I had to separate it off into its own variable. I’m not sure why this didn’t work, but the end result is the same, and the code is perhaps a little less cryptic: