summary_20220809
select count from @table where id = @id;
是否只能用循环日期+动态 sql 处理?
伪代码如下:
create PROCEDURE findMaxDay(id INT, mouth VARCHAR(255);)
begin
-- 省略一些赋值
WHILE x <= 31 DO
set table_name = CONCAT('summary_',mouth, lpad(x,2,0));
-- 查询单表结果并赋值
set sql = CONCAT("select count INTO @tmp from '", table_name, "' where id = '", id,"'");
PREPARE stmt FROM @sql;
EXECUTE stmt;
deallocate prepare stmt;
-- 比较和更新结果
set @day = IF( @tmp > @max, lpad(x,2,0), @day);
set @max = max(tmp, max);
set x = x + 1;
END WHILE;
-- 输出结果
select day;
end
请大佬看看这样的思路对不对?有没有更好的方案。
1
netnr 2022-09-09 18:21:01 +08:00 via Android
还有种方式,用 union all ,需要添加一列表名,外面包一层取 max ,性能未知
|
2
wxf666 2022-09-09 18:31:03 +08:00
好奇,有这个需求,为啥会这样分表。。
|
3
akira 2022-09-09 18:31:48 +08:00
渲染出下面 sql ,然后直接执行就好了呗。 如果你过滤条件都走的索引的话,理论上应该还行
select * from (select 'summary_20220809' , max(id) `max_id` from summary_20220809 union all select 'summary_20220808' , max(id) `max_id` from summary_20220808 union all select 'summary_20220807' , max(id) `max_id` from summary_20220807 union all ... ) a order by `max_id` desc limit 1 |