6

Learning SQL, sorry if this is rudimentary. Trying to figure out a working UPDATE solution for the following pseudoish-code:

UPDATE tableA 
SET tableA.col1 = '$var'
WHERE tableA.user_id = tableB.id
AND tableB.username = '$varName'
ORDER BY tableA.datetime DESC LIMIT 1

The above is more like SELECT syntax, but am basically trying to update a single column value in the latest row of tableA, where a username found in tableB.username (represented by $varName) is linked to its ID number in tableB.id, which exists as the id in tableA.user_id.

Hopefully, that makes sense. I'm guessing some kind of JOIN is necessary, but subqueries seem troublesome for UPDATE. I understand ORDER BY and LIMIT are off limits when multiple tables are involved in UPDATE... But I need the functionality. Is there a way around this?

A little confused, thanks in advance.

4

2 回答 2

17

解决方案是将 ORDER BY 和 LIMIT 作为连接的一部分嵌套在 FROM 子句中。这让您首先找到要更新的确切行 (ta.id),然后提交更新。

UPDATE tableA AS target
    INNER JOIN (
      SELECT ta.id
      FROM tableA AS ta
        INNER JOIN tableB AS tb ON tb.id = ta.user_id
        WHERE tb.username = '$varName'
        ORDER BY ta.datetime DESC
        LIMIT 1) AS source ON source.id = target.id
    SET col1 = '$var';

向 Baron Schwartz(又名 Xaprb)致敬,以获取关于这个确切主题的出色帖子: http ://www.xaprb.com/blog/2006/08/10/how-to-use-order-by-and-limit-在-multi-table-updates-in-mysql/

于 2012-05-11T14:58:47.123 回答
0

您可以使用以下查询语法:

update work_to_do as target
   inner join (
      select w. client, work_unit
      from work_to_do as w
         inner join eligible_client as e on e.client = w.client
      where processor = 0
      order by priority desc
      limit 10
   ) as source on source.client = target.client
      and source.work_unit = target.work_unit
   set processor = @process_id;

这完美地工作。

于 2017-08-29T16:49:20.413 回答