使用mysql merge into 時遇到的mysql #1093錯誤的解決

來源:互聯網
上載者:User

標籤:class   技術分享   eve   分享圖片   cli   存在   closed   position   serve   

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 whereuserid=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
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錯誤的解決

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.