[英]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.