gpt4 book ai didi

mysql - 动态更新表并重新排列记录

转载 作者:可可西里 更新时间:2023-11-01 08:39:39 27 4
gpt4 key购买 nike

我有一张 table 可以说:

**tblHotel**
id
start_date
end_date
rate

现在我想编写更新日期范围记录的程序,例如我有数据:

id   start_date     end_date     rate
1 2016/01/01 2016/01/10 10
2 2016/01/11 2016/01/20 50

现在,如果新的日期范围和费率来自供应商,我想更新表格记录,就像新范围一样。

  start_date   end_date     rate
2016/01/05 2016/01/12 100

现在更新的记录应该是这样的:

id   start_date     end_date     rate
1 2016/01/01 2016/01/04 10
2 2016/01/05 2016/01/12 100
3 2016/01/13 2016/01/20 50

查询

insert into tbl_Hotel(start_date, end_date, rate)
select $start_date, $end_date, $rate
from dual
where not exists (select 1
from tbl_Hotel h
where h.start_date <= $end_date and h.end_date >= $start_date
);

最佳答案

这可能不完全正确 - 和/或它可能有点过于做作 - 但我确信它是沿着正确的路线......

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,start_date DATE NOT NULL UNIQUE
,end_date DATE NOT NULL
,rate INT NOT NULL
);

INSERT INTO my_table VALUES
(1,'2016-01-01','2016-01-10',10),
(2,'2016-01-11','2016-01-20',50);

INSERT INTO my_table
SELECT y.id
, COALESCE(GREATEST(x.start_date,y.start_date),x.start_date) start_date
, COALESCE(LEAST(x.end_date,y.end_date),x.end_date) end_date
, x.rate
FROM
( SELECT a.start_date
, MIN(COALESCE(b.start_date,a.end_date)) end_date
, a.rate
FROM
( SELECT LEAST(start_date,'2016-01-05') start_date, LEAST(end_date,'2016-01-04') end_date, rate FROM my_table
UNION
SELECT GREATEST(start_date,'2016-01-13') start_date, GREATEST(end_date,'2016-01-12') end_date, rate FROM my_table
UNION
SELECT '2016-01-05','2016-01-12',100
) a
LEFT
JOIN
( SELECT LEAST(start_date,'2016-01-05') start_date, LEAST(end_date,'2016-01-04') end_date,rate FROM my_table
UNION
SELECT GREATEST(start_date,'2016-01-13') start_date, GREATEST(end_date,'2016-01-12') end_date,rate FROM my_table
UNION
SELECT '2016-01-05','2016-01-12',100
) b
ON b.start_date < a.end_date
AND b.end_date > a.start_date
AND a.start_date < b.start_date
AND b.rate <> a.rate
GROUP
BY a.start_date
, a.rate
HAVING end_date >= start_date
) x
LEFT
JOIN my_table y
ON y.start_date < x.end_date
AND y.end_date > x.start_date
AND y.rate = x.rate
ON DUPLICATE KEY UPDATE start_date = COALESCE(GREATEST(x.start_date,y.start_date),x.start_date)
, end_date = COALESCE(LEAST(x.end_date,y.end_date),x.end_date);

SELECT * FROM my_table;
+----+------------+------------+------+
| id | start_date | end_date | rate |
+----+------------+------------+------+
| 1 | 2016-01-01 | 2016-01-04 | 10 |
| 2 | 2016-01-13 | 2016-01-20 | 50 |
| 3 | 2016-01-05 | 2016-01-12 | 100 |
+----+------------+------------+------+

请注意,id 不会改变以适应修改后的日期。这是故意的。

关于mysql - 动态更新表并重新排列记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39052732/

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