UPDATE Syntax with ORDER BY, LIMIT and Multiple Tables

后端 未结 2 781
南笙
南笙 2020-12-17 01:01

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

UPDATE tableA 
SET          


        
相关标签:
2条回答
  • 2020-12-17 01:38

    You can use following query syntax:

    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;
    

    This works perfectly.

    0 讨论(0)
  • 2020-12-17 02:02

    The solution is to nest ORDER BY and LIMIT in a FROM clause as part of a join. This let's you find the exact row to be updated (ta.id) first, then commit the update.

    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';
    

    Hat tip to Baron Schwartz, a.k.a. Xaprb, for the excellent post on this exact topic: http://www.xaprb.com/blog/2006/08/10/how-to-use-order-by-and-limit-on-multi-table-updates-in-mysql/

    0 讨论(0)
提交回复
热议问题