mysql - 从sql中获取列名

标签 mysql sql

我有这张 table

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

这样的事情甚至可能吗。

如果您需要更多说明,请告诉我

最佳答案

您可以在不需要值的 select for union 中添加您需要的列和 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;

这样所有的select都有相同的列数和匹配的数据类型

关于mysql - 从sql中获取列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54980486/

相关文章:

mysql - 更新行时是否总是触发生成列的计算?

mysql - 在注册表中找到 MySQL 的通用路径,因为它在注册表中创建特定于版本的条目作为键

java - 如何通过在 java-sql 应用程序中输入所有列数据来过滤搜索?

php - 删除重复的mysql条目

PHP - SQL 不返回行但在本地服务器上工作

php - IS NULL 在列中找不到空行

SQL DateDiff 高级用法?

mysql - 顺序子句中的列 'task_id' 不明确

mysql - spring jpa数据原生Sql查询的问题

mysql - SQL 查询改进 - 仅当 A>B 时才选择 X,其中 A 和 B 值在变量的范围内