我不是MYSQL的专家,主要是在tsql中开发,但我需要编写一段动态代码,根据具体的日期范围给出每个表的记录数。下面的代码为我的数据库中的所有表提供行计数,但我有第二个表,每个表都有一个记录,并说明它是否有一个我可以查询的create_date字段。我想要做的是改变我的代码以查看辅助表,并使用created_date字段(如果可用)来构建select语句。该计划是在程序顶部传递一个日期,并使用该日期仅计算所需字段可用的计数,如果不可用,则将显示总记录数。
希望这已经有了一些意义,任何指针都会受到赞赏,正如我在MYSQL之前所说的那样,我不想做什么,但我想学习。
谢谢P
SET SESSION group_concat_max_len = (1000000);
SET GLOBAL max_allowed_packet = (50*1024*1024);
select
-- Sort the tables by count
concat(
'select * from (',
-- Aggregate rows into a single string connected by unions
group_concat(
-- Build a "select count(1) from db.tablename" per table
concat('select ',
quote(db), ' db, ',
quote(tablename), ' tablename, '
'count(1) "rowcount" ',
'from ', db, '.', tablename)
separator ' union ')
, ') t ')
into @sql
from (
select
table_schema db,
table_name tablename
from information_schema.tables
where table_schema not in
('sampledatabase')
) t;
-- Execute @sql
prepare s from @sql; execute s; deallocate prepare s;
答案 0 :(得分:0)
MySQL实际上有一个表列列表,如果一个表有一列create_date
并且在这种情况下添加一个where
- 条件,你可以查看那里:
set @mydate = '2016-01-01';
select
-- Sort the tables by count
concat(
'select * from (',
-- Aggregate rows into a single string connected by unions
group_concat(
-- Build a "select count(1) from db.tablename" per table
concat('select ',
quote(db), ' db, ',
quote(tablename), ' tablename, ',
'count(1) rowcount, ',
has_createddate, ' filtered ',
'from `', db, '`.`', tablename,'`',
-- add "where" when the column is there
case when has_createddate = 1 then concat(' where create_date ',
-- your filter condition, e.g.
' >= ''', @mydate, '''')
else '' end
)
separator ' union ')
, ') t ')
into @sql
from (
select
t.table_schema db,
t.table_name tablename,
case when not c.COLUMN_NAME is null then 1 else 0 end has_createddate
from information_schema.tables t
left join information_schema.COLUMNS c
on t.table_schema = c.table_schema
and t.table_name = c.table_name
and c.column_name = 'create_date'
where t.table_schema not in ('sampledatabase')
) t;
您可以使用自己的表格使用相同的逻辑。如果您的查阅表中的字段包含您要过滤的列名(而不是常量create_date
),则可以在concat
中使用该列,例如
...
case when not filtercol is null then concat(' where `', filtercol, '`', ' >= ''',
...