Home >Database >Mysql Tutorial >MySql中select from一个将要更新的关系目标_MySQL

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-01 13:44:20956browse

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
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn