您好,欢迎访问一九零五行业门户网

MySql中select from一个将要更新的关系目标_MySQL

bitscn.com
在mysql中如何select from一个将要更新的关系目标:
问题陈述:
在《数据库系统概念第五版》( 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。
错误就是你不能指向并选择一个将要修改或是更新的目标关系。
http://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
)
参考:
http://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/
http://dev.mysql.com/doc/refman/5.0/en/update.html
http://forge.mysql.com/wiki/mysql_internals
bitscn.com
其它类似信息

推荐信息