一、通用方法:information_schema
查询所有表名 ```sql
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'your_database_name';
```
- 替换`your_database_name`为实际数据库名(如`db_name`)。
查询特定数据库的表名
```sql
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'your_database_name'
AND table_type = 'BASE TABLE';
```
- `table_type = 'BASE TABLE'`可排除视图等特殊对象。
二、数据库特定方法
MySQL
- 所有表名: `SHOW TABLES;`(简单快捷,需登录数据库)。 - 特定表名
SQL Server - 所有表名:
`SELECT name FROM sys.tables;`。
- 特定表名:`SELECT name FROM sys.tables WHERE name = 'your_table_name';`。
Oracle - 当前用户表名:
`SELECT table_name FROM user_tables;`。
- 所有表名:`SELECT table_name FROM all_tables;`(需DBA权限)。
PostgreSQL - 所有表名:
`SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';`。
三、扩展查询(如按用户或模式过滤)
包含特定用户的表名(如`username`):
```sql
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name LIKE '%username%';
```
排除系统表:
```sql
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_type = 'BASE TABLE'
AND table_name NOT LIKE 'pg_catalog%';
```
四、注意事项
字符集问题:
建议使用英文表名和字段名,避免因字符集差异导致查询失败。
权限限制:
部分数据库(如Oracle)需DBA权限才能查询系统表。
客户端工具:
建议使用数据库管理工具(如MySQL Workbench、SQL Server Management Studio)图形化查看表名,操作更便捷。
通过以上方法,可灵活查询数据库表名,根据具体需求选择合适的语句和权限设置。