I have this SQL query
Query
x
Select * from `trees` WHERE id = '1' AND ( `apple`='1' OR `banana` = '1' OR `coconut` = '1' OR `pear` ='1') ;
And this is my table let’s say
Tree_table
id | apple | banana | coconut | pear|
1 1 1 1 0
2 0 0 1 1
3 1 0 0 1
So I want my output to be
apple
banana
coconut
Is this possible using SQL query or even PHP will do
Advertisement
Answer
You need to unpivot the data. In MySQL, this is probably most easily done with union all
:
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;