mysql 使用group_concat获取select * 所有字段列名拼接

在使用数据库查询时,很多时候为了省事会使用select * from table ...方式处理,后续如果需要将* 号改成具体的列明时,对于字段特别多的表,如果通过手动一个一个写的话效率会比较低,可以使用group_concat内置函数进行逗号拼接获取*号对应的所有字段列名,如下所示:

查看表字段列:

desc order_info;

获取拼接字段列:

-- 默认逗号分隔,其中table_schema为数据库名,table_name为表名
select group_concat(COLUMN_NAME) as r from information_schema.columns where table_schema = "test" and table_name = "order_info";

如果表名需要别名的话,通过concat函数给列明加上即可:

-- 默认逗号分隔,加上别名前缀
select group_concat(concat("alia.", COLUMN_NAME)) as r from information_schema.columns where table_schema = "test" and table_name = "order_info";

如果想在逗号前加上一个空格的话可以设置分隔符:

-- 按制定分隔符分隔,逗号后加一个空格 
select group_concat(COLUMN_NAME SEPARATOR ", ") as r from information_schema.columns where table_schema = "test" and table_name = "order_info";

若果不需要一些字段的话可以再where条件里加上不想要的字段列:

-- 过滤不想要的字段 
select group_concat(COLUMN_NAME SEPARATOR ", ") as r from information_schema.columns where table_schema = "test" and table_name = "order_info" 
and COLUMN_NAME not in('create_date', 'pay_date');

以此方式便可很好地将*替换成左右字段名拼接效果

附:

存储过程:

BEGIN
    -- SELECT tb;
    set @tb_o = tb;
    SELECT SPLIT_STR(@tb_o, " ", 1) INTO tb;
    -- SELECT tb;    
    set @sql = CONCAT('desc ', db, ".", tb);
    -- SELECT @sql;
   -- sql语句预处理
    PREPARE stmt from @sql;
   -- sql语句执行
    EXECUTE stmt;
    -- 要对一个预制语句解除分配,需使用DEALLOCATE PREPARE语句。尝试在解除分配后执行一个预制语句会导致错误。
    deallocate PREPARE stmt;
   -- 调用分割函数
SELECT SPLIT_STR(@tb_o, " ", 2) INTO alias; -- SELECT alias; if(alias is not null and LENGTH(trim(alias)) > 0) then select CONCAT(alias,".") INTO alias; end if; -- SELECT alias; select group_concat(CONCAT(alias, COLUMN_NAME) SEPARATOR ", ") as r from information_schema.columns where table_schema = db and table_name = tb; END

分割函数:

CREATE FUNCTION SPLIT_STR(
  x VARCHAR(255),
  delim VARCHAR(12),
  pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
       LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
       delim, '');

使用:

# 若有别名则为表名+单空格+别名写法
set @tb = "user a";
SELECT DATABASE() INTO @db;
call SQL_COLUMNS_APPEND(@db, @tb, "");
原文地址:https://www.cnblogs.com/kingsonfu/p/15480615.html