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 can't specify target table 'readbook' for update in FROM clause