简体   繁体   English

来自子查询中同一表的MySQL UPDATE和SELECT

[英]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: 首先,我知道从M​​ySQL 5.1.x开始这是不可能的,它在这里这样说:

http://dev.mysql.com/doc/refman/5.1/en/update.html 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 (which 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 . 如果sol_col > some_othercol我试图最终将some_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. 这会将some_col设置为其自己的值,但是仅当some_col已经大于2时。我知道这不会做任何事情,但是它显示的概念可能更接近您想要的内容。 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. 如果您最后给出了一些详细信息,我可能会帮助您找到更接近您需要的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM