4

我的数据库中有以下结构:

id,col_a,col_b,col_c,etc...

现在,除了 id 之外的所有其他列都是布尔类型。例如,让我们说

col_a=1,
col_b=0,
col_c=1

我正在寻找一种方法来返回列为真 (=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。

4

1 回答 1

3

如果我正确理解你的问题,也许你需要这样的东西:

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               |
...

在此处查看小提琴。如果您需要动态执行此操作,您可以使用以下准备好的语句:

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;

在这里拉小提琴。

于 2013-04-17T07:05:17.037 回答