UPDATE Syntax with ORDER BY, LIMIT and Multiple Tables

后端 未结 2 1263
醉酒成梦
醉酒成梦 2020-12-17 01:11

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:51

    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/

提交回复
热议问题