我有这张 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/