Mysql函式生成查詢分表sql
阿新 • • 發佈:2021-11-08
經常給領導查資料,但是資料庫不少表是分表的,查詢起來貼上複製很麻煩,這裡僅作記錄,之前已經介紹過Mysql儲存過程的使用,和變數宣告,以及分支判斷等。
mysql 儲存過程簡單使用 :https://www.cnblogs.com/jefferyfeng/p/14479399.html
/** * 生成分表查詢語句 * sqls:原始sql,帶有佔位符 * tableNums: 分表個數 * skipType: 跳過分表型別 0.不跳過 1.跳過奇數表 2.跳過偶數表 * replaceStr: 替換佔位符 * * @date 2021-11-08 * @author fdh */ CREATEDEFINER=`root`@`%` FUNCTION `buildSql`(sqls varchar(1000), tableNums int(3), skipType int(1), replaceStr varchar(100)) RETURNS text CHARSET utf8 BEGIN set @oriSql = sqls; set @oriReplaceStr = replaceStr; set @i = 0; set @tempSql = ''; set @replaceSql = ''; -- 迴圈開始 while @i<tableNums DOif (skipType = 1 and mod(@i, 2) = 0) then set @replaceSql := replace(@oriSql, @oriReplaceStr, @i); elseif (skipType = 2 and mod(@i, 2) = 1) then set @replaceSql := replace(@oriSql, @oriReplaceStr, @i); end if; if (skipType = 0 and @replaceSql ='') then set @replaceSql := replace(@oriSql, @oriReplaceStr, @i); end if; if (@tempSql = '' and @replaceSql != '') then set @tempSql := CONCAT(@replaceSql, '\n'); elseif (@tempSql != '' and @replaceSql != '') then set @tempSql := CONCAT(@tempSql, 'union all\n', @replaceSql, '\n'); end if; -- 重置 set @i := @i + 1; set @replaceSql := ''; end while; -- 迴圈結束 RETURN @tempSql; END
使用示例:
select buildSql("select DATE_FORMAT(create_time, '%Y-%m') as months, count(1) as counts from crm_clue_call_record*prefix* where create_time > '2021-11-01 00:00:00' and create_time < '2021-11-08 00:00:00' group by DATE_FORMAT(create_time, '%Y-%m')", 32, 2, "*prefix*");