2025-05-23

 

在MySql中如何select from一個將要更新的關系目標:

問題陳述:

在《數據庫系統概念第五版》(<DatabaseSystem Concepts> Fifth Edition),第三章,3.10.3講SQL的更新,有個例子是:

+————————-+——————–+————+

|account_number | branch_name | balance |

+————————+———————+————+

|A-101                 | Downtown     | 500.00  |

|A-102                 | Perryridge     | 400.00  |

|A-201                 | Brighton        | 900.00  |

|A-215                 | Mianus          | 700.00   |

|A-217                 | Brighton        | 750.00   |

|A-222                 | Redwood        | 700.00  |

|A-305                 | Round Hill     | 350.00   |

+————————+———————-+————+

updateaccount

setbalance = balance * 1.05

wherebalance > (select avg(balance)

fromaccount);

然後就報錯瞭!有沒有!如下:

Youcan't specify target table 'account' for update in FROM clause。

錯誤就是你不能指向並選擇一個將要修改或是更新的目標關系。

https://dev.mysql.com/doc/refman/5.0/en/update.html寫到:

“Currently,you cannot update a table and select from the same table in asubquery.”

但是很多情況下,我想用一些數據要更新一個關系,而這些數據恰好是通過就指向這個關系的子查詢得到的,例如本例子我需要聚集函數算account的balance均值。

 

解決方法:

MySQL會將from從句中子查詢的衍生關系(derivedtable)實體化成一個臨時表(temporarytable),所以我們將(selectavg(balance) from account) 再套入一個from從句即可:

updateaccount

setbalance = balance * 1.05

wherebalance >( select avg(tmp.balance)

from (select * from account ) as tmp

)

 

參考:

https://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/

https://dev.mysql.com/doc/refman/5.0/en/update.html

https://forge.mysql.com/wiki/MySQL_Internals

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *