mysql不允許select from后面指向用作update的表,有時(shí)候讓人糾結(jié)。當(dāng)然,有比創(chuàng)建無休止的臨時(shí)表更好的辦法。本文解釋如何update一張表,同時(shí)在查詢子句中使用select.
問題描述
假設(shè)我要update的表跟查詢子句是同一張表,這樣做有許多種原因,例如用統(tǒng)計(jì)數(shù)據(jù)更新表的字段(此時(shí)需要用group子句返回統(tǒng)計(jì)值),從某一條記錄的字段update另一條記錄,而不必使用非標(biāo)準(zhǔn)的語句,等等。舉個(gè)例子:
create table apples(variety char(10) primary key, price int);
insert into apples values(‘fuji’, 5), (‘gala’, 6);
update apples
??? set price = (select price from apples where variety = ‘gala’)
??? where variety = ‘fuji’;
錯(cuò)誤提示是:error 1093 (hy000): you can’t specify target table ‘apples’ for update in from clause. mysql手冊(cè)u(píng)pdate documentation這下面有說明 : “currently, you cannot update a table and select from the same table in a subquery.”
在這個(gè)例子中,要解決問題也十分簡(jiǎn)單,但有時(shí)候不得不通過查詢子句來update目標(biāo)。好在我們有辦法。
解決辦法
既然mysql是通過臨時(shí)表來實(shí)現(xiàn)from子句里面的嵌套查詢,那么把嵌套查詢裝進(jìn)另外一個(gè)嵌套查詢里,可使from子句查詢和保存都是在臨時(shí)表里進(jìn)行,然后間接地在外圍查詢被引用。下面的語句是正確的:
update apples
? set price = (
????? select price from (
??????? select * from apples
????? ) as x
????? where variety = ‘gala’)
? where variety = ‘fuji’;
?以上就是MySQL數(shù)據(jù)庫(kù)在select同時(shí)進(jìn)行update操作的方法的內(nèi)容,更多相關(guān)內(nèi)容請(qǐng)關(guān)注PHP中文網(wǎng)(www.php.cn)!