我需要使用 SQL 查询检查数据库是否完全为空(没有表)。这怎么办?
感谢您的帮助!
SELECT COUNT(DISTINCT `table_name`) FROM `information_schema`.`columns` WHERE `table_schema` = 'your_db_name'
将返回数据库中表(或视图)的实际数量。 如果该数字为 0,则没有表。
select count(*)
from information_schema.tables
where table_type = 'BASE TABLE'
and table_schema = 'your_database_name_here'
在 MYSQL 中:
use DATABASE;
show tables;
获取 MySQL 中所有没有表的数据库的列表:
use information_schema
select schema_name from `schemata` s
left join `tables` t on s.schema_name = t.table_schema
where t.table_name is null
;
干杯,克里斯蒂安
如果您使用的是 SQL Server 2005 或更高版本,则可以使用系统视图之一来为当前数据库实现此目的:
select Count(*)
from sys.tables
where [type] = 'U'
SQLServer 实现:
USE database_name
SELECT COUNT(*) from information_schema.tables
WHERE table_type = 'base table'
“select * from information_schema.tables”将为您提供大多数数据库上的表列表。
在甲骨文中: 从 user_tables 中选择 Count(*)
我需要一些可以给我在 Bash 中使用的退出代码的东西。这是建立在@longneck 的可靠答案的基础上的。如果数据库有表,则
select
语句会将 contents
列设置为“有表”。在这种情况下,Grep 将返回成功的 0
,否则将返回非零。
#!/bin/bash
user=username
pw=passwd
db=database
mysql -u ${user} -p"${pw}" -D ${db} --execute="SELECT CASE COUNT(*) WHEN '0' THEN 'empty database' ELSE 'has tables' END AS contents FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND table_schema = '${db}';" | grep 'has tables'
echo $?
在bash中:
db_name='my_db'
mysql -s --skip-column-names -e "SELECT COUNT(DISTINCT table_name) FROM information_schema.columns WHERE table_schema = '$db_name'"
解决方案:为了验证您的数据库不为空,您可以查看表列表并测量其中的实例。
首先:执行与数据库的简单连接
mysql -u <userName> -p
,运行show databases;
使用use <databaseName>;
选择您的数据库,然后运行show tables;
并期望获得表列表。
+----------------------------------------+
| Tables_in_databaseName |
+----------------------------------------+
| databaseA |
| databaseB |
| databaseC |
+----------------------------------------+
第二:对sql上的主键/主表执行简单的计数操作并计数实例:
select count(*) from <primaryKeyColumn>;
计数结果应> 0
+----------+
| count(*) |
+----------+
| 100 |
+----------+
对于 MySQL 8,我必须将查询调整为:
SELECT COUNT(*) from information_schema.tables
WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA=DATABASE();