从每个表中选择3个结果

时间:2013-02-22 11:25:31

标签: mysql

假设数据库中有大量的表(200+),我如何执行SELECT * FROM <> LIMIT 3; <>表示数据库中的所有表?我的目标是了解每个表包含的内容,DESCRIBE中显示的列名称不是特别有用。因此,我希望从每个表中看到3条记录。

我知道我可以通过迭代show tables;的输出轻松地在PHP中编写脚本但是我正在寻找在MySQL解释器上运行的命令(mysql>提示符)。

1 个答案:

答案 0 :(得分:1)

在此链接下详细描述(虽然我自己没有尝试过,但它只是在我的书签中):

http://www.youdidwhatwithtsql.com/mysql-clone-of-sp_msforeachtable/624

DELIMITER $$

DROP PROCEDURE IF EXISTS `usp_mysql_foreachtable`$$

CREATE PROCEDURE `usp_mysql_foreachtable`(IN sql_string VARCHAR(1000))
    LANGUAGE SQL
    NOT DETERMINISTIC
    COMMENT 'Functional clone of sp_MsForEachTable'
    BEGIN

    DECLARE var_tablename VARCHAR(100);
    DECLARE last_row BIT;

    DECLARE table_cursor CURSOR FOR SELECT TABLE_NAME
                    FROM information_schema.TABLES
                    WHERE TABLE_TYPE = 'BASE TABLE'
                    AND TABLE_SCHEMA = DATABASE();

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET last_row = 1;

    OPEN table_cursor;
    FETCH table_cursor INTO var_tablename;

    SET last_row = 0;
    SET @var = '';

    lbl_table_cursor: LOOP

        SET @qry = REPLACE(sql_string, '?', var_tablename);

        PREPARE q FROM @qry;
        EXECUTE q;
        DEALLOCATE PREPARE q;

        FETCH table_cursor INTO var_tablename;
        IF last_row = 1 THEN
            LEAVE lbl_table_cursor;
        END IF;
    END LOOP lbl_table_cursor;

    CLOSE table_cursor;

    END$$

DELIMITER ;

然后用

调用它
CALL usp_mysql_foreachtable('SELECT * FROM ? LIMIT 3;');