mysql插入表是否存在 [英] mysql insert into table if exists
问题描述
在我的项目中,我有两个代码路径在首次设置时与MySQL交互.第一步是数据库结构的创建,在这里,用户可以选择所需的功能,并且某些表可能最终无法在数据库中创建,具体取决于用户选择的内容.
In my project I have two code paths that interact with MySQL during first time setup. The first step is the database structure creation, in here, a user has the ability to pick and choose the features they want - and some tables may not end up being created in the database depending on what the user selects.
在第二部分中,我需要用一些基本数据预加载 did 创建的表-仅在表存在的情况下,如何才能将行插入这些表中?
In the second part, I need to preload the tables that did get created with some basic data - how could I go about inserting rows into these tables, only if the table exists?
我知道IF NOT EXISTS
,但是据我所知,这仅适用于创建表,我正在尝试做类似的事情
I know of IF NOT EXISTS
but as far as I know, that only works with creating tables, I am trying to do something like this
INSERT INTO table_a ( `key`, `value` ) VALUES ( "", "" ) IF EXISTS table_a;
这是通过包含很多条目的文件加载的,因此,当表不存在时让它抛出错误是不可能的.
This is loaded through a file that contains a lot of entries, so letting it throw an error when the table does not exist is not an option.
推荐答案
IF (SELECT count(*)FROM information_schema.tables WHERE table_schema ='databasename'AND table_name ='tablename') > 0
THEN
INSERT statement
END IF
使用信息模式检查表是否存在
Use information schema to check existence if table
这篇关于mysql插入表是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!