1

我正试图让 MySQL 将所有在某个时间没有预订的讲师归还给我。此查询本质上是搜索查询。因此,返回所有基本上尚未预订的教练及其详细信息。有人可以帮我完成它吗?

SELECT
  AddressTypes.AddressTypeName,
  Addresses.*,
  InstructorSettings.*,
  Users.*,
  BookedSlots.DateTime
FROM Users
  LEFT OUTER JOIN InstructorSettings
    ON Users.UserID = InstructorSettings.UserID
  LEFT OUTER JOIN Addresses
    ON Users.UserID = Addresses.UserID
  INNER JOIN AddressTypes
    ON Addresses.AddressTypeID = AddressTypes.AddressTypeID
  LEFT OUTER JOIN BookedSlots
    ON Users.UserID = BookedSlots.UserID
WHERE Users.AccountTYpe = 3 AND Addresses.PostCode1 IN ('l13') AND BookedSlots.DateTime <> '2013-04-25 11:00:00'

上面的查询没有返回任何内容,但如果我取出“AND BookedSlots.DateTime <> '2013-04-25 11:00:00'”,它会返回所有讲师的详细信息。

数据库

4

2 回答 2

0

要检查特定时间段上没有任何预订,请在加入条件中包含时间段并选择时间段 id 为空的位置 - 如下所示:

SELECT
  AddressTypes.AddressTypeName,
  Addresses.*,
  InstructorSettings.*,
  Users.*,
  BookedSlots.DateTime
FROM Users
  LEFT OUTER JOIN InstructorSettings
    ON Users.UserID = InstructorSettings.UserID
  LEFT OUTER JOIN Addresses
    ON Users.UserID = Addresses.UserID
  INNER JOIN AddressTypes
    ON Addresses.AddressTypeID = AddressTypes.AddressTypeID
  LEFT OUTER JOIN BookedSlots
    ON Users.UserID = BookedSlots.UserID AND 
                      BookedSlots.DateTime = '2013-04-25 11:00:00'
WHERE Users.AccountTYpe = 3 AND 
      Addresses.PostCode1 IN ('l13') AND 
      BookedSlots.UserID is null
于 2013-04-25T13:36:33.203 回答
0

在我看来,您正在寻找的是在指定时间内 BookedSlots中不存在记录

我不确定这是否被认为是 MySQL 最佳实践,但我通常不是使用 a join,而是使用子选择或临时表来完成该任务,如下所示:

SELECT
  AddressTypes.AddressTypeName,
  Addresses.*,
  InstructorSettings.*,
  Users.*,
FROM Users
  LEFT OUTER JOIN InstructorSettings
    ON Users.UserID = InstructorSettings.UserID
  LEFT OUTER JOIN Addresses
    ON Users.UserID = Addresses.UserID
  INNER JOIN AddressTypes
    ON Addresses.AddressTypeID = AddressTypes.AddressTypeID
WHERE Users.AccountType = 3 AND Addresses.PostCode1 IN ('l13') 
AND Users.UserID not in (SELECT BookedSlots.InstructorID FROM BookedSlots 
     WHERE BookedSlots.DateTime = '2013-04-25 11:00:00')

编辑:根据评论,将选择语句更改为排除 BookedSlots,并将子选择更改为返回 InstructorId(在预订时匹配教师而不是学生)。

于 2013-04-24T22:06:29.773 回答