Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Disponibilidade de reserva do MySQL, intervalos de datas sobrepostos


  1. Construa uma lista de todos os limites de reserva (ou seja, datas de início e término) que ocorrem no período desejado:
      SELECT date_start AS boundary
      FROM   bookings
      WHERE  date_start BETWEEN @start AND @end
    UNION
      SELECT date_end
      FROM   bookings
      WHERE  date_end BETWEEN @start AND @end
    

  2. Adicione a isso o limite que ocorre imediatamente antes do período desejado:
    -- [ from part 1 above ]
    UNION
      SELECT MAX(boundary)
      FROM (
        SELECT MAX(date_start) AS boundary
        FROM   bookings
        WHERE  date_start <= @start
      UNION ALL
        SELECT MAX(date_end)
        FROM   bookings
        WHERE  date_end <= @end
      ) t
    

  3. Faça uma junção externa entre este resultado e as bookings mesa, mantendo todos os limites, mas apenas incluindo uma reserva se contribuir para o número de pessoas simultâneas depois o limite:
    FROM bookings RIGHT JOIN (
      -- [ from part 2 above ]
    ) t ON date_start <= boundary AND boundary < date_end
    

  4. Some o número de pessoas em cada fronteira:
    SELECT IFNULL(SUM(quantity),0) AS simultaneous_people
    -- [ from part 3 above ]
    GROUP BY boundary
    

  5. Encontre o máximo e o mínimo:
    SELECT MIN(simultaneous_people),
           MAX(simultaneous_people)
    FROM (
      -- [ from part 4 above ]
    ) t
    

Juntando tudo:
SELECT MIN(simultaneous_people),
       MAX(simultaneous_people)
FROM (
  SELECT IFNULL(SUM(quantity),0) AS simultaneous_people
  FROM   bookings RIGHT JOIN (
    SELECT date_start AS boundary
    FROM   bookings
    WHERE  date_start BETWEEN @start AND @end
  UNION
    SELECT date_end
    FROM   bookings
    WHERE  date_end BETWEEN @start AND @end
  UNION
    SELECT MAX(boundary)
    FROM (
      SELECT MAX(date_start) AS boundary
      FROM   bookings
      WHERE  date_start <= @start
    UNION ALL
      SELECT MAX(date_end)
      FROM   bookings
      WHERE  date_end <= @end
    ) t
  ) t ON date_start <= boundary AND boundary < date_end
  GROUP BY boundary
) t

Veja em sqlfiddle .