insert之前判断表中有没有此数据

https://www.cnblogs.com/liaojie970/p/4962025.html

INSERT INTO vrv_paw_template(templateName,templateFileName,createTime,updateTime) 
SELECT '自定义','policycustom',NOW(),NOW() 
FROM DUAL WHERE NOT EXISTS (
    SELECT 1 FROM vrv_paw_template WHERE templateName='自定义' OR templateFileName='policycustom' LIMIT 1
);

注释:dual 是个临时表

mysql官方对这个表的解释吧(http://dev.mysql.com/doc/refman/5.0/en/select.html):

    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.

官方的解释说:纯粹是为了满足select … from…这一习惯问题,mysql会忽略对该表的引用。

把我发现的三个应用地方都加上:
    select express from dual #这条sql就类似上面的查看系统时间一样。把express替换成表达式或函数就行
    select express from dual where condition #这条sql只是对上面的一点扩展 加上一个where条件。其实这个where条件跟我们平时使用的where条件没什么区别。执行的时候也是先判断where子句是否成立,满足然后再执行select中的express,最后返回express执行的值;如果where子句不成立,则返回空。比如:select 1+1 from where 1=1,将返回2。
    第三个就是一条比较实用的SQL语句了!你否想过:插入数据时先判断一下这条 记录是否已存在这个问题!?也许很多时候为了解决这个问题,你会先select一下,根据他的结果再决定是否继续写入数据库。但是用dual这个表,可以让你仅一条SQL就可以解决这个问题哦!
    SQL就是这样写的:

    INSERT INTO table  (primarykey, field1, field2, ...)  SELECT key, value1, value2, ...  FROM dual  WHERE not exists (select * from table where primarykey = id);

猜你喜欢

转载自blog.csdn.net/yuyeqianhen/article/details/89379056