我的数据库中有以下结构:
id,col_a,col_b,col_c,etc...
现在,除了id之外的所有其他列都是boolean类型。让我们说例如
col_a=1,
col_b=0,
col_c=1
我正在寻找一种方法来返回列为true(= 1)的列的名称,因此在此示例中,返回应类似于col_a,col_c
将会有一个动态数量的列,因为表经常被更改以添加新列并删除旧列。
到目前为止我的函数看起来像这样 - 它应该是返回该列名称的函数...
DROP FUNCTION fn_access;
DELIMITER //;
CREATE FUNCTION fn_access (myid INT) RETURNS varchar(800)
DETERMINISTIC
BEGIN
DECLARE ret_val VARCHAR(800);
DECLARE col_name VARCHAR(255);
DECLARE i INT;
DECLARE num_rows INT;
DECLARE col_names CURSOR FOR
SELECT column_name
FROM information_schema.columns
WHERE `table_name` = 'access' AND `table_schema` = 'some_db' AND `column_name` <> 'id'
ORDER BY ordinal_position;
SELECT FOUND_ROWS() into num_rows;
SET i = 1;
the_loop: LOOP
IF i > num_rows THEN
CLOSE col_names;
LEAVE the_loop;
END IF;
FETCH col_names
INTO col_name;
SET ret_val = CONCAT(',' col_name);
SET i = i + 1;
END LOOP the_loop;
SELECT * FROM access WHERE id = @myid;
RETURN ret_val;
END
//
有没有办法使用直接SQL?我正在使用MySQL。
答案 0 :(得分:2)
如果我理解你的问题,也许你需要这样的事情:
SELECT 'col_a' col
FROM yourtable
WHERE col_a
UNION
SELECT 'col_b'
FROM yourtable
WHERE col_b
UNION
SELECT 'col_c'
FROM yourtable
WHERE col_c
...
这将返回表格中至少有一行为真的所有列。
或许这个:
SELECT
id,
CONCAT_WS(', ',
CASE WHEN col_a THEN 'col_a' END,
CASE WHEN col_b THEN 'col_b' END,
CASE WHEN col_c THEN 'col_c' END) cols
FROM
yourtable
将以此格式返回行:
| ID | COLS |
----------------------------
| 1 | col_a, col_c |
| 2 | col_a, col_b, col_c |
| 3 | |
| 4 | col_c |
...
请参阅小提琴here。如果你需要动态地执行它,你可以使用这个准备好的语句:
SELECT
CONCAT(
'SELECT id, CONCAT_WS(\', \',',
GROUP_CONCAT(
CONCAT('CASE WHEN ',
`COLUMN_NAME`,
' THEN \'',
`COLUMN_NAME`,
'\' END')),
') cols FROM yourtable'
)
FROM
`INFORMATION_SCHEMA`.`COLUMNS`
WHERE
`TABLE_NAME`='yourtable'
AND COLUMN_NAME!='id'
INTO @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
小提琴here。