如果表存在,则创建它,如果不存在,则创建它

时间:2022-01-31 08:10:37

I'm stumped, I don't know how to go about doing this.

我被难住了,我不知道该怎么做。

Basically I just want to create a table, but if it exists it needs to be dropped and re-created, not truncated, but if it doesn't exist just create it.

基本上,我只是想创建一个表,但是如果它存在,它需要被删除和重新创建,而不是被截断,但是如果它不存在,就创建它。

Would anyone be able to help?

有人能帮忙吗?

Thanks, George

谢谢你,乔治。

2 个解决方案

#1


191  

Just put DROP TABLE IF EXISTS `tablename`; before your CREATE TABLE statement.

如果存在“tablename”,只需放置DROP TABLE;在创建表语句之前。

That statement drops the table if it exists but will not throw an error if it does not.

如果该语句存在,则该语句将删除该表,但如果它不存在,则不会抛出错误。

#2


28  

Just use DROP TABLE IF EXISTS:

如果存在,就使用DROP TABLE:

DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` ( ... );

Try searching the MySQL documentation first if you have any other problems.

如果您有任何其他问题,请尝试先搜索MySQL文档。

#1


191  

Just put DROP TABLE IF EXISTS `tablename`; before your CREATE TABLE statement.

如果存在“tablename”,只需放置DROP TABLE;在创建表语句之前。

That statement drops the table if it exists but will not throw an error if it does not.

如果该语句存在,则该语句将删除该表,但如果它不存在,则不会抛出错误。

#2


28  

Just use DROP TABLE IF EXISTS:

如果存在,就使用DROP TABLE:

DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` ( ... );

Try searching the MySQL documentation first if you have any other problems.

如果您有任何其他问题,请尝试先搜索MySQL文档。