简体   繁体   中英

Mysql Join on Previous Row With Matching Foreign Key

I've got a table, as such:

|id|jobid|statusid| ... other irrelevant rows...
|1 |123  | 1      |
|2 |321  | 2      |
|3 |123  | 2      |
|4 |321  | 3      |
|5 |123  | 3      |

Due to some unfortunate user error, they ended up using (for example) status 3 on some 500 jobs when the policy is to use status 4 following a status 2.

How would I go about joining a row to the previous row matching its value in the column "jobid" when there is an uncertain distance between it and the row before it, given that the value in "statusid" is 3? The goal being to update the table so that any 3 following a 2 with the same jobid (regardless of distance between ids) will be changed to a 4.

My desired output would be to join row 4 and 2 as well as 5 and 3. (I'm aware the example is consistently id-2, that is not the case in my database.)

So far the relationship would be

SELECT mt.id, mt3.id
FROM mytable mt
INNER JOIN (SELECT MAX(mt1.id) AS mid, mt1.jobid
                    FROM mytable mt1
                    WHERE mt1.id < mt.id
                    GROUP BY mt1.jobid) mt2
    ON mt2.jobid = mt.jobid
INNER JOIN mytable tm3
    ON mt3.id=mt2.mid
        AND mt3.statusid = 2
WHERE mt.statusid=3

But the line in the subquery reading "WHERE sh1.id < mt.id" is a relationship that can't exist as mt.id originated outside the subquery.

How can I get this query to work?

Thank you!

You can join to the previous row using a correlated subquery and another join. The following puts the two records on the same row:

select t.*, tprev.*
from (select t.*,
             (select t2.id
              from mytable t2
              where t2.jobid = t.jobid and t2.id < t.id
              order by t2.id desc
              limit 1
             ) as prev_id
      from mytable t
     ) t left join
     mytable tprev
     on t.id = tprev.prev_id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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