gpt4 book ai didi

用于识别表中序列的 ​​MySql 查询

转载 作者:行者123 更新时间:2023-11-29 02:28:48 24 4
gpt4 key购买 nike

我需要有关 mysql 查询的帮助,以根据一系列进入和退出日期更新同一表的新列。

下表:

╔════╦═══════════╦═════════════╦═════════════╦════════════════════╗
║ ID ║ PLACE ║ ENTRYDATE ║ EXITDATE ║ LAST_PLACE_VISITED ║
╠════╬═══════════╬═════════════╬═════════════╬════════════════════╣
║ 1 ║ Delhi ║ 1-Jan-2012 ║ 5-Jan-2012 ║ ║
║ 1 ║ Agra ║ 10-Jan-2012 ║ 11-Jan-2012 ║ ║
║ 1 ║ Bangalore ║ 21-Jan-2012 ║ 24-Jan-2012 ║ ║
║ 1 ║ Mumbai ║ 12-Jan-2012 ║ 19-Jan-2012 ║ ║
║ 2 ║ LA ║ 1-Mar-2012 ║ 3-Mar-2012 ║ ║
║ 2 ║ SFO ║ 10-Mar-2012 ║ 14-Mar-2012 ║ ║
║ 2 ║ NY ║ 4-Mar-2012 ║ 9-Mar-2012 ║ ║
║ 3 ║ Delhi ║ 12-Apr-2012 ║ 13-Apr-2012 ║ ║
╚════╩═══════════╩═════════════╩═════════════╩════════════════════╝

ENTRYDATE 和 EXITDATE 的数据类型是DATE

根据上表,我需要编写一个查询以根据 ID 的进入和退出日期更新“Last_Place_Visited”列。

如果您对此查询有任何帮助,我们将不胜感激。

谢谢。巴尔加夫

最佳答案

因为 MySQL 不支持窗口函数,所以这是一个非常困惑的问题,

UPDATE  TravelTbl a
INNER JOIN
(
SELECT a.ID,
a.Place,
a.EntryDate,
a.ExitDate,
b.Place Last_Place_Visited
FROM
(
SELECT ID,
Place,
EntryDate,
ExitDate,
Last_Place_Visited,
@grp := if(@ID = ID, @grp ,0) + 1 GRP_RecNo,
@ID := ID
FROM TravelTbl,
(SELECT @ID := '', @grp := 0) vars
ORDER BY EntryDate
) a
LEFT JOIN
(
SELECT ID,
Place,
EntryDate,
ExitDate,
Last_Place_Visited,
@grp2 := if(@ID2 = ID, @grp2 ,0) + 1 GRP_RecNo,
@ID2 := ID
FROM TravelTbl,
(SELECT @ID2 := '', @grp2 := 0) vars
ORDER BY EntryDate
) b ON a.ID = b.ID AND
a.GRP_RecNo = b.GRP_RecNo + 1
) b ON a.ID = b.ID AND
a.Place = b.Place AND
a.EntryDate = b.EntryDate AND
a.ExitDate = b.ExitDate AND
b.Last_Place_Visited IS NOT NULL
SET a.Last_Place_Visited = b.Last_Place_Visited

输出

╔════╦═══════════╦═════════════╦═════════════╦════════════════════╗
║ ID ║ PLACE ║ ENTRYDATE ║ EXITDATE ║ LAST_PLACE_VISITED ║
╠════╬═══════════╬═════════════╬═════════════╬════════════════════╣
║ 1 ║ Delhi ║ 1-Jan-2012 ║ 5-Jan-2012 ║ (null) ║
║ 1 ║ Agra ║ 10-Jan-2012 ║ 11-Jan-2012 ║ Delhi ║
║ 1 ║ Bangalore ║ 21-Jan-2012 ║ 24-Jan-2012 ║ Mumbai ║
║ 1 ║ Mumbai ║ 12-Jan-2012 ║ 19-Jan-2012 ║ Agra ║
║ 2 ║ LA ║ 1-Mar-2012 ║ 3-Mar-2012 ║ (null) ║
║ 2 ║ SFO ║ 10-Mar-2012 ║ 14-Mar-2012 ║ NY ║
║ 2 ║ NY ║ 4-Mar-2012 ║ 9-Mar-2012 ║ LA ║
║ 3 ║ Delhi ║ 12-Apr-2012 ║ 13-Apr-2012 ║ (null) ║
╚════╩═══════════╩═════════════╩═════════════╩════════════════════╝

关于用于识别表中序列的 ​​MySql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16313977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com