gpt4 book ai didi

mysql - 如何找到超过 2 个用户的匹配时间间隔

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

从不同用户的给定时间间隔中找到最合适的时间。

Rows: 5
fid userid FromDateTime ToDateTime flag
62 1 2012-07-18 01:48:20 2012-07-18 02:55:20 1
63 1 2012-07-18 10:30:46 2012-07-18 12:54:46 1
64 1 2012-07-18 18:50:24 2012-07-18 20:35:24 1
67 1 2012-07-18 15:03:36 2012-07-18 16:03:36 1
68 2 2012-07-18 21:10:47 2012-07-18 23:10:47 1

上表显示了不同用户可用的不同免费时间段,例如:

user1

有空
2012-07-18 01:48:20   to   2012-07-18 02:55:20 , 
2012-07-18 10:30:46 to 2012-07-18 12:54:46
......

用户 2 仅在此时间段内免费:

2012-07-18 21:10:47   to   2012-07-18 23:10:47 

现在我想找出一个最佳时间间隔,双方用户都可以在这个时间间隔内安排他们的 session 。

最佳答案

要查找 user1 和 user2 何时都空闲,请尝试以下操作:

select 
a.datetime_start as user1start,a.datetime_end as user1end,
b.datetime_start as user2start,b.datetime_end as user2end ,
case when a.datetime_start > b.datetime_start then a.datetime_start
else b.datetime_start end as avail_start,
case when a.datetime_end>b.datetime_end then b.datetime_end
else a.datetime_end end as avail_end
from users a inner join users b on
a.datetime_start<=b.datetime_end and a.datetime_end>=b.datetime_start
and a.userid={user1} and b.userid={user2}

SQL FIDDLE HERE.

编辑:要比较 2 个以上的用户,请尝试以下操作:

select max(datetime_start) as avail_start,min(datetime_end) as avail_end
from(
select *,
@rn := CASE WHEN @prev_start <=datetime_end and @prev_end >=datetime_start THEN @rn ELSE @rn+1 END AS rn,
@prev_start := datetime_start,
@prev_end := datetime_end
from(
select * from users2 m
where exists ( select null
from users2 o
where o.datetime_start <= m.datetime_end and o.datetime_end >= m.datetime_start
and o.id <> m.id
)
and m.userid in (2,4,3,5)
order by m.datetime_start) t,
(SELECT @prev_start := -1, @rn := 1, @prev_end=-1) AS vars
) c
group by rn
having count(rn)=4 ;

需要根据用户数改变m.userid in (2,4,3,5)having count(rn)=4

SQL FIDDLE HERE

关于mysql - 如何找到超过 2 个用户的匹配时间间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11965455/

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