PHPeer
PHPeer

Reputation: 659

UPDATE Syntax with ORDER BY, LIMIT and Multiple Tables

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.

Upvotes: 6

Views: 10747

Answers (2)

hmjha
hmjha

Reputation: 489

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.

Upvotes: 0

PHPeer
PHPeer

Reputation: 659

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/

Upvotes: 17

Related Questions