从SQL获取列名

时间:2019-03-04 09:44:46

标签: mysql sql

我有这张桌子

id | apple | banana | coconut | pear| code | Class |
1     1       1       1           0    101      B
2     0       0        1          1    102      C
3     1       0        0          1    103      B

我目前有这个查询

select tree
from ((select id, 'apple' as tree
       from trees
       where apple = 1
      ) union all
      (select id, 'banana' as tree
       from trees
       where banana = 1
      ) union all
      (select id, 'coconut' as tree
       from trees
       where coconut = 1
      ) union all
      (select id, 'pear' as tree
       from trees
       where pear = 1
      )
     ) t
where id = 1;

这给了我输出

apple
banana 
coconut

但是我想做的就是使用code进行查询 WHERE code = '101' and id =1并同时显示class 输出应该像

   class  |fruits
     B      apple 
            banana  
            coconut

甚至是可能的。

让我知道是否需要更多说明

1 个答案:

答案 0 :(得分:0)

您可以添加所需的列,并在不需要值的联合选择中添加null

select tree
from ((select id, 'apple' as tree, code, class
       from trees
       where apple = 1
      ) union all
      (select id, 'banana' as tree, null, null
       from trees
       where banana = 1
      ) union all
      (select id, 'coconut' as tree, null,  null
       from trees
       where coconut = 1
      ) union all
      (select id, 'pear' as tree, null, null
       from trees
       where pear = 1
      )
     ) t
where id = 1;

通过这种方式,所有选择的列数和数据类型都相同