2016-11-16 72 views
0

我不是MYSQL的专家,主要在tsql中开发,但我需要编写一段动态代码,它会根据特定的日期范围给出每个表的记录数。下面的代码给了我数据库中所有表的行数,但是我有第二个表,每个表都有一个记录,并说明它是否有我可以查询的create_date字段。我想要做的是改变我的代码来查看辅助表,并使用created_date字段(如果可用的话)构建select语句。计划是在过程的顶部传递一个日期,并使用该日期来计算仅在必填字段可用时的计数,如果不可用,则将显示总记录数。动态mysql记录计数

希望已经有所作为,任何指针都会非常感谢,正如我之前所说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

的MySQL实际上有表列的列表,你可以看看那里如果表中有一栏create_date在这种情况下添加一个where -condition:

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, '`', ' >= ''', 
... 
+0

嗨Solarflare,这是灿烂的,正是我期待的,你每天都在学习新的东西。 – PJD