创建一个mysql表,如果它不存在,否则添加缺少的列?

时间:2018-05-24 18:42:04

标签: mysql

我有一个PHP应用程序,它经常更新并部署到我们的用户。问题是有时更新会添加用户本地表所没有的新表或列。

如何动态创建缺少的表,或者将缺少的列添加到现有表中?我希望这个过程是半自动化的,因为表和列将来总是会改变。

这是我创建表格的代码

CREATE TABLE `comments` (
  `comment_id` int(11) NOT NULL AUTO_INCREMENT,
  `content_id` int(11) DEFAULT '0',
  `body` text,
  `name` text,
  `creation_ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `delta` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`comment_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

2 个答案:

答案 0 :(得分:0)

将您的代码放在一个块中,并从数据字典中检查您的表是否存在。 如果没有,请通过动态SQL执行DDL。

如果表存在,它将确保您的程序不会出错。

答案 1 :(得分:0)

理想情况下,在部署需要这些更改的应用程序更新时,应该部署脚本来更新标准架构。但是,这样可以集成到您的应用程序中......

可以查询information_schema中的“Tables”以查找有关表和列的信息;您可以检查它们是否存在,并获取它们的当前参数(例如列的数据类型)。您可以创建应用程序调用的启动例程来规范化/更新架构。

的伪代码:

If sometable not found in the information schema, create it
else 
  if it doesn't have some column, add the column
  if it doesn't have some other column, add the column
  if it doesn't have an index on x, add an index on x
  and so on...

另一种选择是在架构中有一个版本表......

if version < 1 then run version1 upgrade script
if version < 2 then run version2 upgrade script
and so on ...
update version to last in current script (so updated script knows where to start)