php – 如何查找超过2个用户的匹配时间间隔

前端之家收集整理的这篇文章主要介绍了php – 如何查找超过2个用户的匹配时间间隔前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

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

user1是免费的

  1. 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. ......

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

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

现在我想找出一个用户可以安排会议的最佳时间间隔.

最佳答案
要查找user1和user2都是免费的,请尝试以下操作:

  1. select
  2. 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
  3. else b.datetime_start end as avail_start,case when a.datetime_end>b.datetime_end then b.datetime_end
  4. else a.datetime_end end as avail_end
  5. from users a inner join users b on
  6. a.datetime_start<=b.datetime_end and a.datetime_end>=b.datetime_start
  7. and a.userid={user1} and b.userid={user2}

SQL FIDDLE HERE.

编辑:
要比较超过2个用户,请尝试以下内容

  1. select max(datetime_start) as avail_start,min(datetime_end) as avail_end
  2. from(
  3. 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
  4. from(
  5. select * from users2 m
  6. where exists ( select null
  7. from users2 o
  8. where o.datetime_start <= m.datetime_end and o.datetime_end >= m.datetime_start
  9. and o.id <> m.id
  10. )
  11. and m.userid in (2,4,3,5)
  12. order by m.datetime_start) t,(SELECT @prev_start := -1,@rn := 1,@prev_end=-1) AS vars
  13. ) c
  14. group by rn
  15. having count(rn)=4 ;

需要根据用户数更改(2,5)中的m.userid并使count(rn)= 4.

SQL FIDDLE HERE

猜你在找的MySQL相关文章