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

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

有人能帮忙吗?


只是使用下降表,如果存在:

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

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


只要把DROP TABLE IF EXISTS ' tablename ';在CREATE TABLE语句之前。

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


嗯…嗯。多年来,没有人提及一件微妙的事情。

DROP TABLE IF EXISTS ' bla ';创建表bla(…); 看起来很合理,但这会导致旧表已经消失而新表还没有创建的情况:一些客户端可能会在此时尝试访问主题表。

更好的方法是创建一个全新的表,并与旧表交换(表内容丢失):

CREATE TABLE `bla__new` (id int); /* if not ok: terminate, report error */
RENAME TABLE `bla__new` to `bla`; /* if ok: terminate, report success */
RENAME TABLE `bla` to `bla__old`, `bla__new` to `bla`;
DROP TABLE IF EXISTS `bla__old`;

You should check the result of CREATE ... and do not continue in case of error, because failure means that other thread didn't finish the same script: either because it crashed in the middle or just didn't finish yet -- it's a good idea to inspect things by yourself. Then, you should check the result of first RENAME ... and do not continue in case of success: whole operation is successfully completed; even more, running next RENAME ... can (and will) be unsafe if another thread has already started same sequence (it's better to cover this case than not to cover, see locking note below). Second RENAME ... atomically replaces table definition, refer to MySQL manual for details. At last, DROP ... just cleans up the old table, obviously.

用SELECT GET_LOCK('__upgrade', -1)这样的语句包装所有语句;... 做RELEASE_LOCK(“__upgrade”);允许在没有错误检查的情况下顺序调用所有语句,但我不认为这是一个好主意:MySQL中的复杂性增加和锁定函数对于基于语句的复制是不安全的。

如果表数据应该在表定义升级中存活…一般情况下,比较表定义以找出差异并产生适当的ALTER要复杂得多。语句,这并不总是自动实现的,例如当列被重命名时。

附注1: 您可以使用相同的方法处理视图,在这种情况下,CREATE/DROP TABLE仅仅转换为CREATE/DROP VIEW,而RENAME TABLE保持不变。事实上,你甚至可以把表格转换成视图,反之亦然。

CREATE VIEW `foo__new` as ...; /* if not ok: terminate, report error */
RENAME TABLE `foo__new` to `foo`; /* if ok: terminate, report success */
RENAME TABLE `foo` to `foo__old`, `foo__new` to `foo`;
DROP VIEW IF EXISTS `foo__old`;

附注2: MariaDB用户应该很乐意使用CREATE OR REPLACE TABLE/VIEW,它已经关心主题问题,而且它的要点很好。


我需要删除一个表并用视图中的数据重新创建。 我从视图中创建了一个表,这是我所做的:

DROP TABLE <table_name>;
CREATE TABLE <table_name> AS SELECT * FROM <view>;

上面的工作为我使用MySQL MariaDb。