Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        6年前关闭。
                                                                                            
                
        
好的,我有一个包含5列的简单表。

ID-否-文本-类型-DependentID
21-1-文字1-8
24-2-文本2-2
32-3-文字3-3
34-4-文字4-6
44-5-文字5-7
33-6-文字3-1
38-7-文字4-8
45-8-文字5-7


要求:系统将从上至下读取(基于ASC订单号),如果看到一行具有Type> 3的行,则它将查找前一个最近的行,该行具有type = 1或2或3,如果它找到一个,然后会将先前的壁橱类型(1/2/3)的ID放入DependentID,如果未找到任何先前的最近的壁橱类型1/2/3,则将0放入DependentID。

注意:对于类型= 1,2,3的行,它不会更新。

因此,更新后的结果将如下所示:

ID-否-文本-类型-DependentID
21-1-文字1-8-0
24-2-文本2-2
32-3-文字3-3
34-4-文字4-6-32
44-5-文字5-7-32
33-6-文字3-1
38-7-文字4-8-33
45-8-文字5-7-33


那么,在这种情况下,如何执行Update查询以使ID生效呢?

我们可以在mysql中使用会话变量来做到这一点吗?

最佳答案

您可以使用相关子查询获取先前的从属ID:

select t.*,
       (select id
        from table t2
        where t2.type in (1, 2, 3) and
              t2.no < t.no
        order by t2.no desc
        limit 1
       ) as NewdependentID
from table t
where t.type > 3;


(实际上,这没有给出NULL的匹配,但这没关系。)

您可以将此查询放入带有联接的update中:

update table t join
       (select t.*,
               (select id
                from table t2
                where t2.type in (1, 2, 3) and
                      t2.no < t.no
                order by t2.no desc
                limit 1
               ) as NewDependentID
        from table t
        where t.type > 3
       ) tdep
       on t.no = tdep.no
    set t.DependentID = coalesce(tdep.NewDependentID, 0);

07-24 09:37
查看更多