根据从其他表引用的多个时序获取表数据

时间:2014-10-17 13:17:55

标签: mysql sql

我有2个表,其中一个表有计划,其他表有可用时间。结构如下

tbl_schedules

id   Int
userid   Int
schedulefrom   Datetime
scheduletill   Datetime


tbl_useravailability

id
userid
availablefrom
availabletill

在同一天的tbl_useravailability中,用户可以有多行。也就是说,用户可以从2014:10:17 05:00:00 to 2014:10:17 12:00:00, 2014:10:17 15:00:00 to 2014:10:17 18:00:00, 2014:10:17 19:00:00 to 2014:10:17 23:00:00

获得

面临的挑战是在给定的可用日期从计划表中选择其他用户的计划,例如where userid <> 1;

2 个答案:

答案 0 :(得分:1)

如下所示(在http://sqlfiddle.com/#!2/f94e6/1/0查看示例):

SELECT
    S.id AS scheduleid,
    S.userid,
    S.schedulefrom,
    S.scheduletill,
    UA.id AS availabilityid,
    UA.availablefrom,
    UA.availabletill
FROM
    tbl_schedules AS S
JOIN tbl_useravailability AS UA
    ON  S.userid = UA.userid
    AND S.schedulefrom >= UA.availablefrom
    AND S.scheduletill <= UA.availabletill
WHERE
    S.userid <> 1

这将向您显示其可用性在其计划期间内的所有用户。

答案 1 :(得分:0)

感谢您花费大量精力来解决此问题。我已经对您的查询进行了一些修改并使其工作。感谢

SELECT
    S.id AS scheduleid,
    S.userid,
    S.schedulefrom,
    S.scheduletill,
    UA.id AS availabilityid,
    UA.availablefrom,
    UA.availabletill
FROM
    tbl_schedules AS S
JOIN tbl_useravailability AS UA
    ON S.schedulefrom between  UA.availablefrom and UA.availabletill

WHERE
    UA.userid=1 and s.userid <> 1