1

this is phpmyadmin table : user_test_detail this is phpmyadmin table : user_test_detail

I want result like below

(
[1] => option_a
[2] => option_d
[3] => option_e
[4] => option_d
)
4
  • 2
    It is not clear what you are trying to achieve here. Commented Jul 5, 2016 at 5:51
  • 1,2,3,4 is question_id and option_a, option_d, option_e, option_d are values. It shows where value is 1 that field name will come in front of question_id Commented Jul 5, 2016 at 5:53
  • Is this all the columns in table user_test_detail? Commented Jul 5, 2016 at 5:55
  • yes, column name want to get in values Commented Jul 5, 2016 at 5:57

2 Answers 2

1

GET IT form information schema

mysql> SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME="TEST";
+-------------+
| COLUMN_NAME |
+-------------+
| user_id     |
| NAME        |
| value       |
+-------------+
3 rows in set (0.00 sec)
Sign up to request clarification or add additional context in comments.

Comments

1

Try this.

select 
    case
        when option_a = '1' then `option_a`
        when option_b = '1' then `option_b`
        when option_c = '1' then `option_c`
        when option_d = '1' then `option_d`
        when option_e = '1' then `option_e`
    end as colName
from user_test_detail
order by question_id

This is only for this 5 columns in table user_test_detail, and if you will change this table's structure in the future, you have to use dynamic sql.

Edited:

select 
    max(case when question_id = 1 then colName end) as `1`,
    max(case when question_id = 2 then colName end) as `2`,
    max(case when question_id = 3 then colName end) as `3`,
    max(case when question_id = 4 then colName end) as `4`
from (
    select 
        case
            when option_a = '1' then `option_a`
            when option_b = '1' then `option_b`
            when option_c = '1' then `option_c`
            when option_d = '1' then `option_d`
            when option_e = '1' then `option_e`
        end as colName,
        question_id
    from user_test_detail
    order by question_id
) t
-- group by question_id

6 Comments

you can get it form information schema no need to write complex query
@MaheshMadushanka Did you realize he did not want all the columns in table, but columns with value is 1 and order by question_id?
yes aggred it was not mention in the initial question
hello 10086, not getting field name in colName. Right now colName value is 1 as per 4 question.
@TerryBabuSamuel What do you mean about 'not working'?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.