要查詢MySQL中所有表的行數,您可以使用以下方法:
DELIMITER //
CREATE PROCEDURE count_rows()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE tableName CHAR(255);
DECLARE rowCount BIGINT;
DECLARE cur CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE();
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
CREATE TEMPORARY TABLE temp_row_counts (tableName VARCHAR(255), rowCount BIGINT);
OPEN cur;
read_loop: LOOP
FETCH cur INTO tableName;
IF done THEN
LEAVE read_loop;
END IF;
SET @sql = CONCAT('SELECT COUNT(*) INTO @rowCount FROM ', tableName);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
INSERT INTO temp_row_counts VALUES (tableName, @rowCount);
END LOOP;
CLOSE cur;
SELECT * FROM temp_row_counts;
END//
DELIMITER ;
這將創建一個名為count_rows
的存儲過程,該過程將遍歷當前數據庫中的所有表,并計算每個表的行數。
CALL count_rows();
這將返回一個結果集,其中包含每個表的名稱及其對應的行數。請注意,這種方法可能需要一些時間才能在大型數據庫上完成。