Mysql
 sql >> Base de données >  >> RDS >> Mysql

Récupérer tous les noms de table, les noms de colonne et les valeurs de colonne à partir d'une base de données spécifique

Pour obtenir table_name et les noms de colonnes, vous pouvez utiliser :

SELECT
 CONCAT(`table_name`, '-',
    GROUP_CONCAT(`column_name` ORDER BY ordinal_position SEPARATOR ':')) AS result
FROM information_schema.columns
-- WHERE `table_name` = ?
GROUP BY `table_name`;

SqlFiddleDemo

Sortie :

╔══════════════╗
║    result    ║
╠══════════════╣
║ tab0-id:col  ║
║ tab1-id:col2 ║
║ tab2-id:col3 ║
╚══════════════╝

Pour obtenir un exemple d'enregistrement pour chaque colonne, vous devez utiliser dynamic-sql :

SET @sql = '';

SELECT @sql := CONCAT(@sql, 
                      '(SELECT ''', `table_name`, ''' AS tab_name, ''', 
                                 `column_name`, ''' AS column_name, ',
                                 `ordinal_position`, ' AS ordinal_pos, ',
                                 `column_name`, ' AS sample '
                       'FROM ', `table_name` ,         
                       ' LIMIT 1) UNION ALL ')
FROM information_schema.columns
WHERE `table_name` LIKE 'tab_';

SET @sql := SUBSTRING(@sql, 1, LENGTH(@sql) - 11);

SET @final_sql = 
'SELECT CONCAT(`tab_name`, ''-'',
    GROUP_CONCAT(CONCAT(`column_name`, '':'', sample ) ORDER BY ordinal_pos)) 
    AS result
 FROM ( <placeholder> ) AS sub
 GROUP BY tab_name';

SET @final_sql = REPLACE(@final_sql, '<placeholder>', @sql);

prepare s from @final_sql;
execute s;

deallocate prepare s;

SqlFiddleDemo2 SqlFiddleDemo3

Sortie :

╔════════════════════════════╗
║           result           ║
╠════════════════════════════╣
║ tab0-id:1,col:a            ║
║ tab1-id:10,col2:2          ║
║ tab2-id:20,col3:2016-01-26 ║
╚════════════════════════════╝