MySQL:如果存在IF表,则截断并插入ELSE创建 [英] MySQL: IF table exists, truncate and insert ELSE create

查看:146
本文介绍了MySQL:如果存在IF表,则截断并插入ELSE创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅使用MySQL(我本质上没有PHP知识),我需要有一个表,该表本质上是更大表的子集.源表不时更改,丢失一些条目,获得其他新条目,并且为现有条目更改值.我可以描述我想发生的事情,但是似乎无法弄清楚使它起作用的命令语法.我也知道我可以有两个独立的查询,并且可以运行我需要的任何一个查询,而且已经解决了,但是我想尽可能地将它们合并.这就是我想要的:

Working only with MySQL (I have essentially no PHP knowledge), I need to have a table that's essentially a subset from a much larger table. The source table changes from time to time, losing some entries, gaining other new ones, and values changing for existing ones. I can describe what I want to happen, but can't seem to figure out a syntax of commands to make it work. I also know I can have two separate queries and just run whichever one I need, and I have that worked out, but I'd like to combine them if possible. Here's what I want:

如果不存在subset_table,请将其创建为[选择查询],否则将截断subset_table并插入[选择查询]

IF the subset_table DOES NOT EXIST, create it as [select query], ELSE truncate the subset_table and insert [select query]

就像我说的那样,我知道还有其他方法可以执行此操作-如果存在/创建,我可以删除它,或者我可以只运行两个不同的sql文件.我只想知道我是否可以按照上面的说明进行操作.

Like I said, I know there are other ways to do this - I could drop if exists/create, or I could just have two different sql files to run. I just want to know if I can do this as specified above.

有想法吗?

推荐答案

您可以执行以下操作:

create table if not exists <tablename> . . .;

truncate table <tablename>;

insert into <tablename>(cols)
    select blah blahblah . . .;

您根本不需要任何if语句.

You don't need any if statements at all.

这篇关于MySQL:如果存在IF表,则截断并插入ELSE创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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