[英]Mysql create view with progressively increment a datetime field
我想在 mysql 的兩個表之間創建一個視圖。
表1
| id_tbl1 | start_date | delay |
+---------+---------------------+-------+
| 1 | 2019-10-11 10:00:00 | 30 |
| 2 | 2019-10-12 18:00:00 | 0 |
表2
| id_tbl2 | id_tbl1 | user |
+---------+------------------+
| 1 | 1 | Andy |
| 2 | 1 | Luke |
| 3 | 2 | Joe |
| 4 | 1 | Susy |
| 5 | 2 | Rick |
我想通過添加延遲字段的值來逐步增加日期時間字段。
結果應該是這樣
視圖1
| id_tbl1 | user | start_date |
+---------+-------+------------------+
| 1 | Andy | 2019-10-11 10:00:00 |
| 1 | Luke | 2019-10-11 10:00:30 |
| 1 | Susy | 2019-10-11 10:01:00 |
| 2 | Joe | 2019-10-12 18:00:00 |
| 2 | Rick | 2019-10-12 18:00:00 |
編輯-我想增加秒數
是否有可能做到這一點?
我怎么能那樣做?
謝謝
您可以使用join
和row_number()
來解決這個問題:
select
t1.id_tbl1,
t2.usr,
date_add(
t1.start_date,
interval (t1.delay * (row_number() over(partition by t1.id_tbl1 order by t2.id_tbl2 ) - 1)) second
) start_date
from tbl1 t1
inner join tbl2 t2 on t1.id_tbl1 = t2.id_tbl1
注意: user
不是列名的好選擇,因為它可能與保留字沖突。 我將其更改為usr
。
with
tbl1 as (
select 1 id_tbl1, '2019-10-11 10:00' start_date, 30 delay from dual
union all select 2, '2019-10-12 18:00', 0 from dual
),
tbl2 as (
select 1 id_tbl2, 1 id_tbl1, 'Andy' usr from dual
union all select 2, 1, 'Luke' from dual
union all select 3, 2, 'Joe' from dual
union all select 4, 1, 'Susy' from dual
union all select 5, 2, 'Rick' from dual
)
select
t1.id_tbl1,
t2.usr,
date_add(
t1.start_date,
interval (t1.delay * (row_number() over(partition by t1.id_tbl1 order by t2.id_tbl2 ) - 1)) second
) start_date
from tbl1 t1
inner join tbl2 t2 on t1.id_tbl1 = t2.id_tbl1;
| id_tbl1 | usr | start_date |
| ------- | ---- | ------------------- |
| 1 | Andy | 2019-10-11 10:00:00 |
| 1 | Luke | 2019-10-11 10:00:30 |
| 1 | Susy | 2019-10-11 10:01:00 |
| 2 | Joe | 2019-10-12 18:00:00 |
| 2 | Rick | 2019-10-12 18:00:00 |
這是您的查詢,您可以將延遲列添加為start_date
字段的interval
。
select t1.id_tbl1 , t1.user
, case when t1.id_tbl2 = 1 then t1.start_date
else t1.start_date + interval t2.delay * (id_tbl2 - 1) second end
from tbl2 t1
left join tbl1 t2 on t1.id_tbl1 = t2.id_tbl1
或者由於您正在創建一個視圖,您可能想要加入一個變量。
select t1.id_tbl1 , t1.user
, t1.start_date
+ interval t2.delay * (@curRow:=@curRow + 1) second
- interval t2.delay second
from tbl2 t1
left join tbl1 t2 on t1.id_tbl1 = t2.id_tbl1
join (select @curRow := 0) r;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.