2013-02-22 58 views
0

假設數據庫的表的數據量很大(200+),我該如何執行SELECT * FROM <> LIMIT 3;,其中<>代表數據庫中的所有表?我的目標是瞭解每個表格包含的內容,並且DESCRIBE中顯示的列名稱不是特別有用。所以我想看看每個表格的3條記錄。從每個表中選擇3個結果

我知道我可以通過遍歷show tables;的輸出來輕鬆地在PHP中編寫腳本,但是我正在尋找一個命令在MySQL解釋器上運行(mysql>提示符)。

回答

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;'); 
+0

叫它謝謝!鏈接的網站還有其他一些精彩的文章。 – dotancohen 2013-02-22 12:51:26