mysql 从创建表SQL中获取表名

cxfofazt  于 2023-05-28  发布在  Mysql
关注(0)|答案(2)|浏览(221)

现在我想从create table sql中获取表名,例如

CREATE TABLE `engineers` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(255) COLLATE utf8mb4_general_ci NOT NULL,
  `password` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
  `email` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
  `birth` datetime,
  PRIMARY KEY (`id`),
  INDEX(`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci

CREATE TABLE IF NOT EXISTS .....
jhkqcmku

jhkqcmku1#

如果您可以查询数据库服务器的information_schema,则可以从以下查询的结果中访问表名。

select  table_name,
        create_time AS `Time` 
from information_schema.tables 
where table_schema = @dbName
order by create_time desc 
limit 1

这应该在表创建完成后立即运行

table_name      Time
table_20200815  15.08.2020 12:06:25

DEMO

bvuwiixz

bvuwiixz2#

这是在php中,但应该很容易转换为ruby。假设Create语句在$sql中...
[已编辑以允许“(”跟在tablename之后,并修复strpos()中的参数顺序]

$tablename = trim(substring($sql,strpos($sql,"TABLE IF NOT EXISTS") === 0 ? strpos($sql,"TABLE") + 5 : strpos($sql,"TABLE IF NOT EXISTS") + 20));
    $tablename = substring($tablename,0,strpos($tablename,strpos($tablename," ") < strpos($tablename,"(") ? " " : "("));

然后测试和剥离反勾,如果有任何。

相关问题