MySql-如果不存在则创建表吗? [英] MySql - Create Table If Not Exists Else Truncate?

查看:963
本文介绍了MySql-如果不存在则创建表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是更新的问题:

当前查询正在执行以下操作:

the current query is doing something like:

$sql1 = "TRUNCATE TABLE fubar";
$sql2 = "CREATE TEMPORARY TABLE IF NOT EXISTS fubar SELECT id, name FROM barfu";

第一次运行包含此方法的方法时,由于该表尚不存在,它将在截断时生成一条错误消息.

The first time the method containing this is run, it generates an error message on the truncate since the table doesn't exist yet.

我唯一的选择是执行CREATE TABLE,运行TRUNCATE TABLE,然后填写表格吗? (3个独立的查询)

Is my only option to do the CREATE TABLE, run the TRUNCATE TABLE, and then fill the table? (3 separate queries)

原始问题是:

我一直很努力地尝试找出MySql中是否可能在不编写块sql的情况下进行以下操作:

I've been having a hard time trying to figure out if the following is possible in MySql without having to write block sql:

CREATE TABLE fubar IF NOT EXISTS ELSE TRUNCATE TABLE fubar

如果我在创建表之前单独运行truncate,但该表不存在,则会收到错误消息.我试图消除该错误消息,而不必添加任何其他查询.

If I run truncate separately before the create table, and the table doesn't exist, then I get an error message. I'm trying to eliminate that error message without having to add any more queries.

此代码将使用PHP执行.

This code will be executed using PHP.

推荐答案

shmuel613,最好是更新您的原始问题,而不是答复.最好是在一个地方包含完整的问题,而不要在讨论中分散讨论.

shmuel613, it would be better to update your original question rather than replying. It's best if there's a single place containing the complete question rather than having it spread out in a discussion.

本的答案是合理的,除了他似乎不想回答的地方有一个不"的意思.仅在不存在存在的情况下删除表是不太正确的.

Ben's answer is reasonable, except he seems to have a 'not' where he doesn't want one. Dropping the table only if it doesn't exist isn't quite right.

您确实需要多个语句.有条件创建然后填充:

You will indeed need multiple statements. Either conditionally create then populate:

  1. 如果不存在则创建临时表fubar(id int,名称varchar(80))
  2. TRUNCATE TABLE fubar
  3. 将其插入fubar SELECT * FROM barfu

或者只是拖放并重新创建

or just drop and recreate

  1. 如果存在则删除表
  2. 创建临时表fubar SELECT ID,名称为barfu

使用纯SQL,这是您的两种实际解决方案.我喜欢第二种.

With pure SQL those are your two real classes of solutions. I like the second better.

(通过存储过程,您可以将其简化为一条语句.类似:TruncateAndPopulate(fubar),但是到编写TruncateAndPopulate()的代码时,您将花费更多的时间,而不仅仅是使用上面的SQL.)

(With a stored procedure you could reduce it to a single statement. Something like: TruncateAndPopulate(fubar) But by the time you write the code for TruncateAndPopulate() you'll spend more time than just using the SQL above.)

这篇关于MySql-如果不存在则创建表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆