如果 MySQL 中不存在则添加列
我认为这非常简单,但仅当这些列不存在时我才尝试运行此命令:
ALTER TABLE `surveytable` ADD IF NOT EXISTS Survey_Name_Qualtrics VARCHAR(20);
ALTER TABLE `surveytable` ADD IF NOT EXISTS Survey_URL_Qualtrics VARCHAR(600);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是我使用的代码,如果 ALTER 列上不存在,我认为您不能使用。
另一种选择是,如果您尝试插入已经存在的列,您可以观察出现的错误,我认为是 1062。并处理该错误。
当然,更好的方法是一开始就不出现错误。
This is the code that i use, i dont think you can use if not exists on a ALTER column.
An alternative you can watch for the error you get if you try to insert a column that already exists, i think its 1062. And handle the error.
Of course the better way is to not get the error in the first place.
这在互联网上随处可见。基本思想是检查您的列的系统表
INFORMATION_SCHEMA.COLUMNS
。我假设“不存在”仅适用于列的名称。http://snippets.dzone.com/posts/show/4663
http:/ /www.genexbs.com/blog/gbs.php/2008/08/09/how-to-check-if-column-exists-in-mysql-t
This is all over the internet. Basic idea is to check the system table
INFORMATION_SCHEMA.COLUMNS
for your column. I'm assuming "none exists" applies to the name of the column only.http://snippets.dzone.com/posts/show/4663
http://www.genexbs.com/blog/gbs.php/2008/08/09/how-to-check-if-column-exists-in-mysql-t
另一个直接的查询是告诉MySQL忽略查询期间出现的任何问题。
Another straight forward query for this would be to tell MySQL to IGNORE any issues that comes up during the query.
diagnonalbatman 的答案对我不起作用;当我尝试时,MySQL 5.7 会抱怨语法错误。它可能在早期版本的 MySQL 中运行良好,但该评论毕竟已经有 8 年多了。
经过一番尝试和错误,这就是我最终得到的结果:
The answer by diagnonalbatman did not work for me; MySQL 5.7 would complain about syntax errors when I tried it. It probably worked fine with an earlier version of MySQL, but the comment is more than 8 years old after all.
After some trial and error, this is what I ended up with: