gpt4 book ai didi

mysql - 选择符合条件的列名 (MySQL)

转载 作者:可可西里 更新时间:2023-11-01 08:20:12 25 4
gpt4 key购买 nike

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

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

现在,除了 id 之外的所有其他列都是 boolean 类型。比方说

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。

最佳答案

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

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

请参阅 fiddle 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;

fiddle here .

关于mysql - 选择符合条件的列名 (MySQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16053425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com