MySQL UPDATE and SELECT from same table in subquery
First off, I know this is impossible as of MySQL 5.1.x, it says so right here:
http://dev.mysql.com/doc/refman/5.1/en/update.html
What I'm asking though is if there is a clever way to execute a query using either a temporarily table/view without having to resort to writing a quick script to do the work. My query (w开发者_C百科hich is COMPLETELY WRONG and DOES NOT work, just an FYI for folks trying this at home) looks something like this:
UPDATE some_table
set some_col = ( SELECT some_othercol
from some_table
WHERE some_col > some_othercol
);
I'm trying to ultimately set some_col
to the value of some_othercol
if sol_col > some_othercol
.
What's the best way to handle this without resorting to a script?
EDIT My subquery returns more than one row!
I don't really understand why you need a subquery. Doesn't this do what you want?:
UPDATE some_table
SET some_col = some_othercol
WHERE some_col > some_othercol
I'm not sure if this is quite what you're trying to do, but maybe I can show you something to put you on the right path.
UPDATE some_table ST
SET some_col = (
SELECT some_col
FROM some_table OT
WHERE OT.ID = ST.ID
)
WHERE ST.some_col > 2
That will set some_col to its own value, but only when some_col is already greater than 2. I know this doesn't do anything, but it shows a concept that may be closer to what you're looking for. If you give some more detail as to what you what to happen in the end, I can possibly help you find a solution closer to what you need.
http://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/ is the best resource I know on that subject.
精彩评论