使用mysql merge into 时遇到的mysql #1093错误的解决

Posted 无论是在网上还是现实中我都是孤独的

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用mysql merge into 时遇到的mysql #1093错误的解决相关的知识,希望对你有一定的参考价值。

2018年2月11日15:34:23

php开发时,要写一个SQL语句。就是如果表中存在相应的记录时,就执行更新,不存在就执行插入。

记得以前做SQL SERVER时,有merge into 语句,可以按查询条件,选择要执行的操作,是插件还是更新。但是mysql好像没这个功能。它是按主键是是否存在进行辨别的。

所以习惯性地写了如下语句:

INSERT INTO readbook (readid,readpage,readcount,bookid,userid,readtime) VALUES ( (SELECT  readid From readbook where
userid=1 and bookid=1 and readpage=5),5,1,1,1,now()) ON duplicate key UPDATE 

readcount=readcount + 1,readtime=now()

结果提示错误,如下:

技术分享图片
静态分析:

分析时发现11个错误。

Unrecognized keyword. (near "key" at position 185)
Unexpected token. (near "=" at position 209)
Unexpected token. (near "readcount" at position 210)
Unexpected token. (near "+" at position 220)
Unexpected token. (near "1" at position 222)
Unexpected token. (near "," at position 223)
Unexpected token. (near "readtime" at position 224)
Unexpected token. (near "=" at position 232)
Unrecognized keyword. (near "now" at position 233)
Unexpected token. (near "(" at position 236)
Unexpected token. (near ")" at position 237)
SQL 查询: 文档

INSERT INTO readbook (readid,readpage,readcount,bookid,userid,readtime) VALUES ( (SELECT readid From readbook where userid=1 and bookid=1 and readpage=5) ,5,1,1,1,now()) ON duplicate key UPDATE readcount=readcount + 1,readtime=now()

MySQL 返回: 文档

#1093 - You cant specify target table readbook for update in FROM clause
error code

于是更改语句:

INSERT INTO readbook (readid,readpage,readcount,bookid,userid,readtime) VALUES ( (SELECT * from (SELECT readid From readbook where userid=1 and bookid=1 and readpage=5) as a ),5,1,1,1,now()) ON duplicate key UPDATE readcount=readcount + 1,readtime=now()

提示插入成功。

之所以能成功是因为,1093错误为:但修改一个表的时候子查询不能是同一个表,解决办法:把子查询再套一层,变成原来表的孙子查询就可以了

其实,这个过程中,由于对Mysql不熟悉,我还遇到了其它很多问题。

比如 

(SELECT * from (SELECT readid From readbook where userid=1 and bookid=1 and readpage=5) as a

必须有 as a ,因为必须给表起个别名,但我以前使用SQL SERVER时,没这个要求。

还有就是,原来我还这么写过

INSERT INTO readbook (readid,readpage,readcount,bookid,userid,readtime) VALUES ( (SELECT 

CASE WHEN a.readid>0 THEN a.readid ELSE NULL END from(SELECT readid From readbook where 

userid=1 and bookid=1 and readpage=3) as a) ,3,1,1,1,now()) ON duplicate key UPDATE 

readcount=readcount + 1,readtime=now()

后来逐渐尝试,发现这个CASE WEHN是没有必要的,貌似MYSQL能自动把查不到结果的值,以默认值代替。

以上是关于使用mysql merge into 时遇到的mysql #1093错误的解决的主要内容,如果未能解决你的问题,请参考以下文章

merge into using 详解

Mysql中有类似merge into的函数吗?

Oracle中merge into的使用

Merge Into 语句代替Insert/Update在Oracle中的应用实战

Oracle中merge into的用法

merge into语句的使用