根据列的值获取MySQL表的列

时间:2015-02-25 01:51:15

标签: php mysql

我正在尝试检索以下格式的表的列名:

id | error 1 | error 2 | error 3 | error 4 |
--------------------------------------------
 1 |    1    |    0    |    0    |    1    |
-------------------------------------------
 2 |    0    |    0    |    0    |    0    |

我需要检索值为1的列名。而不是 “从表中选择*,其中id ='someid'”,然后过滤掉,有没有办法直接从查询中点击列名?

2 个答案:

答案 0 :(得分:0)

虽然只是执行正常的SQL查询然后处理PHP代码中的数据会更好 MUCH ,但可以在这里使用CASE子句在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

答案 1 :(得分:0)

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