MySQL – Creating Column Names from Other Table Rows

MySQL

i have following code, for this i have two tables, one table contain questions and another table contain answers.
answers table something like following : (ans_question_1 to ans_question_95)

| answersId| ans_question_1| ans_question_2| student_id
|-----------|------------  |---------      |
| 1         | Male         | 23            |11
| 2         | Female       | 21            |12

Questions table (questions 1 to 95)

| question_id | Question| 
|-----------  |--------  
| 1           | Gender       
| 2           | Area code  

Want table something like this (need stored procedure with parameter student_id)
i also need this table creation dynamically, because my number of questions change regularly.

| student_id  | Gender    | Area Code
|-----------  |--------  -|--------
| 11          | Male      | 23
| 12          | Female    | 21

Best Answer

Using same stored procedure from previous answer, you can generate a new columns names, casting ans_question_xx with the name of each question.

create procedure getStudentAnswers(StudentId int)
begin

    set @cols := (select group_concat('ans_question_',
                                       cast(question_id as char(20)), 
                                       ' as ', 
                                       question separator ', ') 
                  from questions);                           

    set @sql = concat('select student_id,  ', 
                      @cols, 
                      ' from   answers
                        where student_id = ', cast(StudentId as char(20)), 
                      ' order by student_id;');

    PREPARE dynamic_statement FROM @sql;
    EXECUTE dynamic_statement;
    set @sql := null;
    set @cols := null;
    DEALLOCATE PREPARE dynamic_statement;

end \\

call getStudentAnswers(11);

call getStudentAnswers(12);

| student_id | Gender | Area_code | Another_question |
|------------|--------|-----------|------------------|
| 11         | Male   | 23        |                  |

| student_id | Gender | Area_code | Another_question |
|------------|--------|-----------|------------------|
| 12         | Female | 21        | null             |

Rextester here