繁体   English   中英

MySQL:更新条件和选择语句

[英]MySQL: Update on condition and select statement

我有带有 id、degree、roundAbout 和 action 的表。 我需要根据下一行的度数和动作值更新动作。 为了解释,需要做这样的事情。 如果当前度数小于下一行度数且 roundAbout 为“N”动作应设置为“右转”,如果当前度数大于下一行度数且 roundAbout 为“N”动作应设置为“左转”且如果 nxt行 roundAbout 是 'y' 然后不管程度动作都应该设置为 'FollowRoundAbout'

我如何实现这一目标? 这是我的桌子的例子

ID   |   degree  |  roundabout|
----------------------------
 1   |    30     |  N         |
 2   |   130     |  N         |
 3   |   330     |  N         |
 4   |   210     |  N         |
 5   |    30     |  Y         |

My expected table would be

ID   |   degree  |  roundabout|   action|
-----------------------------------------
 1   |    30     |  N         |   RIGHT
 2   |   130     |  N         |   RIGHT
 3   |   330     |  N         |   LEFT
 4   |   210     |  N         |   FollowRound
 5   |    30     |  Y         |   Stop

这听起来像是带有窗口函数的case表达式:

select t.*,
       (case when next_roundabout = 'Y'
             then 'Follow Roundabout'
             when degree < next_degree and roundabout = 'N'
             then 'TurnRight'
             when degree > next_degree and roundabout = 'N'
             then 'TurnLeft'
             when next_degree is null
             then 'Stop'
        end) as action
from (select t.*,
             lead(degree) over (order by id) as next_degree,
             lead(roundabout) over (order by id) as next_roundabout
      from t
     ) t;

如果您有action列,您可以将此结果保存到新表(或视图)或更新现有表。

对于 MySql 8.0+,您可以使用 LEAD() 窗口函数和自连接来完成:

UPDATE tablename t1
INNER JOIN (
  SELECT *, 
         LEAD(degree) OVER (ORDER by ID) next_degree,
         LEAD(roundabout) OVER (ORDER by ID) next_roundabout
  FROM tablename
) t2 ON t2.id = t1.id
SET t1.action = CASE
  WHEN t2.next_roundabout = 'Y' THEN 'FollowRound'
  WHEN t1.degree < t2.next_degree AND t1.roundAbout = 'N' THEN 'RIGHT'
  WHEN t1.degree > t2.next_degree AND t1.roundAbout = 'N' THEN 'LEFT'
  ELSE 'STOP'
END; 

请参阅演示
结果:

> ID | degree | roundabout | action     
> -: | -----: | :--------- | :----------
>  1 |     30 | N          | RIGHT       
>  2 |    130 | N          | RIGHT       
>  3 |    330 | N          | LEFT      
>  4 |    210 | N          | FollowRound
>  5 |     30 | Y          | STOP   

解决方案:1

select a.id, a.degree, a.roundabout, case when  a.degree < b.degree and b.roundabout = 'N' then  
'RIGHT'    
when  a.degree > b.degree and b.roundabout = 'N'
THEN 'LEFT'
when  b.roundabout = 'Y' then 'FollowRound'
end
as action
from table1 a crossjoin table2 b
where b.id = a.id + 1

解决方案2:

select a.id, a.degree, a.roundabout, case when  a.degree < b.degree and b.roundabout = 'N' then  
    'RIGHT'    
    when  a.degree > b.degree and b.roundabout = 'N'
    THEN 'LEFT'
    when  b.roundabout = 'Y' then 'FollowRound'
    end
    as action from table a join table b on two.id = one.id + 1 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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