首页 > 解决方案 > 如何使用 MySQL 从数据库中的所有表中提取前几行?

问题描述

我知道如何在 mysql 中一次查询表的前几行。但是我有一个包含 50 多个表的数据库,所以任务变得乏味。我想知道是否有一种方法可以一次将它们全部检索出来?

我知道在 sql server 中我们可以使用这个:

DECLARE @sql VARCHAR(MAX)='';
SELECT @sql=@sql+'SELECT TOP 3 * FROM '+'['+SCHEMA_NAME(schema_id)+'].['+name+']'+';'
  FROM sys.tables
EXEC(@sql);

但我不知道如何使用 mySQL 来做到这一点。

谢谢!

标签: mysqlextraction

解决方案


This is of course not a MySQL-only answer, but since I recently needed to accomplish what OP wants, and I don't see another answer, here's a solution.

mysql [args] -s -e "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='[your_db]'" | xargs -I{} mysql [args] -e "USE [your_db]; SELECT * FROM {} LIMIT 3"

Where [args] are the arguments used for the MySQL command line (host and port and such), and [your_db] is the name of the DB you want to dump.


推荐阅读