如何从架构中的每个列获取示例值

时间:2013-06-01 08:46:05

标签: mysql sql database schema reverse-engineering

我正在对MySQL数据库进行逆向工程,我希望从每个表的每一列中获取一个示例值列表。我想运行这样的查询:

select
  table_name,
  column_name,
  group_concat(
    (select distinct table_name.column_name limit 100)
    separator ','
  ) as examples
from
  information_schema.columns
where
  table_schema = 'myschema'
;

我希望输出看起来像这样:

table1 column1 (123,124,234)
table1 column2 ('Joe','Sara','Bob')

MySQL不接受table_name.column_name作为有效语法。编写此查询的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

我认为山姆,你正在寻找类似的东西,或者至少它会是一个更好的方法:

select
  table_name,
  column_name,
  group_concat((column_name) separator ',') as examples
from
  information_schema.columns
where
  table_schema = 'test'
GROUP BY table_name
;

答案 1 :(得分:0)

根据rene的建议,我编写了一个存储过程,它输出每个表中每列的值示例。这很丑陋,但很有效。我欢迎有关如何改进此代码的建议。

DELIMITER // 
CREATE PROCEDURE column_example_values(
    IN db_name VARCHAR(64), 
    IN tbl VARCHAR(64), 
    IN col VARCHAR(64), 
    OUT result MEDIUMTEXT)
BEGIN
    SET @s = CONCAT('SELECT GROUP_CONCAT(tbl1.',col,
                    ' separator \',\') FROM (SELECT DISTINCT ',
                    col,' FROM ',db_name,'.',tbl,
                    ' LIMIT 100) tbl1 INTO @result1');
    PREPARE stmt FROM @s;
    EXECUTE stmt;
    SET result = IFNULL(@result1,'');
END;
//
DELIMITER ;

DELIMITER // 
CREATE PROCEDURE all_columns_example_values(IN db_name VARCHAR(64))
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE tbl, col VARCHAR(64);

  DECLARE cur1 CURSOR FOR 
    SELECT 
      table_name,
      column_name 
    FROM 
      information_schema.columns 
    WHERE 
      table_schema = db_name 
    ORDER BY 
      table_name, 
      column_name;

  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  CREATE TEMPORARY TABLE results (
    tbl VARCHAR(64), col VARCHAR(64), examples MEDIUMTEXT);

  OPEN cur1;

  read_loop: LOOP
    FETCH cur1 INTO tbl, col;
    IF done THEN
      LEAVE read_loop;
    END IF;
    CALL column_example_values(db_name,tbl,col,@result);
    INSERT INTO results (tbl, col, examples) VALUES (tbl, col, @result);
  END LOOP;

  CLOSE cur1;

  SELECT * FROM results;
  DROP TABLE results;
END;
//
DELIMITER ;

可以用

调用
CALL all_columns_example_values('mydb');