我有这张桌子
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
甚至是可能的。
让我知道是否需要更多说明
答案 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;
通过这种方式,所有选择的列数和数据类型都相同