sql如果在insert语句中没有select [英] sql if in insert statement without select

查看:177
本文介绍了sql如果在insert语句中没有select的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天我问过这个问题:如果在mysql中插入语句并且答案有效很好。
问题是如果值不存在,我需要在表中插入一行。
fe

yesterday I asked this question: if in mysql insert statement and the answer works very well. The problem is that I need to insert a row in my table if a value doesn't exist. f.e.

 If('x' NOT EXIXTS in (select campoX from table) then
 insert into table (...) values (...) etc.

我该怎么办?互联网我找不到答案:(

How can I do? on the internet I can't find an answer :(

推荐答案

我假设您的表名为tbl。

I assume your table is named tbl.

INSERT INTO tbl (campoX ) 
    SELECT 'X' FROM DUAL 
    WHERE NOT EXISTS( 
                      SELECT campoX from tbl 
                      WHERE campoX ='X'
                     );

DUAL 纯粹是为了方便那些要求所有SELECT语句都应该有FROM和可能的其他子句的人.MySQL可能会忽略这些子句。如果没有引用表,MySQL不需要FROM DUAL。

DUAL is purely for the convenience of people who require that all SELECT statements should have FROM and possibly other clauses. MySQL may ignore the clauses. MySQL does not require FROM DUAL if no tables are referenced.

正如其他人提到的,如果你的campoX是unigue或主键字段,你可以在这里使用 INSERT IGNORE 语句。

As some other mentioned, you could use INSERT IGNORE statement here IF your campoX is an unigue Or primary key field.

这篇关于sql如果在insert语句中没有select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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