2016-07-05 43 views
1

這是phpMyAdmin的表中獲取的列名:user_test_detail this is phpmyadmin table : user_test_detail 如何在mysql中

我想導致像下面

(
[1] => option_a 
[2] => option_d 
[3] => option_e 
[4] => option_d 
) 
+2

目前尚不清楚你正試圖在這裏實現什麼。 –

+0

1,2,3,4是question_id,option_a,option_d,option_e,option_d是值。它顯示值爲1的字段名將出現在question_id –

+0

之前這是表user'test_detail中的所有列嗎? – Blank

回答

1

GET IT形成信息模式

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) 
1

試試這個。

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 

這僅適用於在表user_test_detail這5列,如果你將在未來改變這種表的結構,你必須使用動態SQL。

編輯:

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 
+0

你可以得到它的表格信息架構無需編寫複雜的查詢 –

+0

@MaheshMadushanka你是否意識到他不想要表中的所有列,但具有值的列是1,並按' question_id'? – Blank

+0

是的,在最初的問題中沒有提到 –