I'm trying to retrieve the column names of a table of the following format:
id | error 1 | error 2 | error 3 | error 4 |
--------------------------------------------
1 | 1 | 0 | 0 | 1 |
-------------------------------------------
2 | 0 | 0 | 0 | 0 |
I need to retrieve the column name whose value is 1. Instead of doing "Select * from table where id = 'someid'" and then filtering out, is there a way to hit the column names directly from the query?
Although it would be MUCH better to just do a normal SQL query and then process the data in your PHP code, you can use CASE
clauses here to get it done in SQL:
SELECT id,
( CASE WHEN `error 1` = 1 THEN 'error 1' END ),
( CASE WHEN `error 2` = 1 THEN 'error 2' END ),
( CASE WHEN `error 3` = 1 THEN 'error 3' END ),
( CASE WHEN `error 4` = 1 THEN 'error 4' END )
FROM your_table
SELECT id, CONCAT_WS(',',t2.e1,t2.e2,t2.e3,t2.e4) as err FROM table1
INNER JOIN (
SELECT id,
CASE WHEN `error 1`= 1 THEN 'error 1' ELSE NULL END AS e1,
CASE WHEN `error 2`= 1 THEN 'error 2' ELSE NULL END AS e2,
CASE WHEN `error 3`= 1 THEN 'error 3' ELSE NULL END AS e3,
CASE WHEN `error 4`= 1 THEN 'error 4' ELSE NULL END AS e4
FROM table1
) as t2
on table1.id=t2.id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.