2016-11-16 12 views
0

私はMySQLの専門家ではなく、主にtsqlで開発していますが、特定の日付範囲に基づいてテーブルあたりのレコード数を与える動的なコードを書く必要があります。下のコードは、私のデータベース内のすべての私のテーブルの行数を提供しますが、私は各テーブルのレコードを持って、それが私が照会できるcreate_dateフィールドを持っているかどうかを言う2番目のテーブルがあります。私がしたいのは、セカンダリテーブルを見て、select文を構築するために利用可能な場合はcreated_dateフィールドを使用するように私のコードを変更することです。この計画では、プロシージャの最上部にある日付を渡して、その日付を使用して、必要なフィールドが使用可能な場合にのみカウントを計算します。使用できない場合は、合計レコード数が表示されます。レコード数が動的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