mysql-动态sql实现

需求为 :
表中有x列(500列),所有的数据都为0(false)和1(true). 要求统计出其中有x(200)个true的总行数(数据库层面实现)
说明 :
不建议用这种,主要是为了记录动态sql和处理思路.


表结构 :

CREATE TABLE `test2` (
  `id` tinyint(4) DEFAULT 0,
  `id1` tinyint(4) DEFAULT 0,
  `id2` tinyint(4) DEFAULT 0,
  `id3` tinyint(4) DEFAULT 0,
  `id4` tinyint(4) DEFAULT 0,
  `id5` tinyint(4) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

存储过程 :

BEGIN
-- 定义动态sql
declare exec_sql text;
-- 查询所有列(可加where条件进行排除某些列)
SELECT @cols := GROUP_CONCAT(COLUMN_NAME SEPARATOR "+") AS '列字段' FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'test2' AND TABLE_NAME = 'test2';
-- 拼接待执行的动态sql
set exec_sql = concat('select count(1) as ','true为',size,'的行数',' from test2 where ',@cols,'=',size);
-- 准备执行动态sql
set @ms = exec_sql;
prepare stmt from @ms;
-- 执行动态sql
execute stmt;
END

执行 :

CALL true_size(1,@rs);

在这里插入图片描述

发布了67 篇原创文章 · 获赞 10 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_17522211/article/details/96475920
今日推荐