sql >> Database teknologi >  >> RDS >> Mysql

mysql viser ledige tidsslots og tidsslot optaget fra bordet

OK, ren MySQL - så længe man kan lide de tricks. Jeg har brug for en variabel, som initialiseres til "Begyndelsen" af perioderne for at blive vist, noget som now() normalt.

Først blot testdataene:

create table bookingEvents 
   (id int not null primary key auto_increment,
    timeBooked datetime, 
    duration int
   );


insert into bookingEvents values (null, '2013-05-13 13:22:00', 15);
insert into bookingEvents values (null, '2013-05-13 15:10:00', 45);
insert into bookingEvents values (null, '2013-05-13 19:55:00', 30);
insert into bookingEvents values (null, '2013-05-14 03:22:00', 15);
insert into bookingEvents values (null, '2013-05-14 08:19:00', 15);
 

Derefter initialiseres "skyderen":

set @timeSlider='2013-05-10 00:00:00';
 

Vælg derefter:

select if (d.name = 'Free', @timeSlider, b.timeBooked) as free_from,
       if (d.name = 'Free', b.timeBooked, @timeSlider := b.timeBooked + interval b.duration minute) as free_until,
       d.name as Free
from (select 1 as place, 'Free' as name union select 2 as place, 'Booked' as name) d 
inner join bookingEvents b 
having free_from < free_until
order by b.timeBooked, d.place;
 

Resultat:

+---------------------+---------------------+--------+ | free_from | free_until | Free | +---------------------+---------------------+--------+ | 2013-05-10 00:00:00 | 2013-05-13 13:22:00 | Free | | 2013-05-13 13:22:00 | 2013-05-13 13:37:00 | Booked | | 2013-05-13 13:37:00 | 2013-05-13 15:10:00 | Free | | 2013-05-13 15:10:00 | 2013-05-13 15:55:00 | Booked | | 2013-05-13 15:55:00 | 2013-05-13 19:55:00 | Free | | 2013-05-13 19:55:00 | 2013-05-13 20:25:00 | Booked | | 2013-05-13 20:25:00 | 2013-05-14 03:22:00 | Free | | 2013-05-14 03:22:00 | 2013-05-14 03:37:00 | Booked | | 2013-05-14 03:37:00 | 2013-05-14 08:19:00 | Free | | 2013-05-14 08:19:00 | 2013-05-14 08:34:00 | Booked | +---------------------+---------------------+--------+

Hvis du har et givet sluttidsstempel, skal du forudindstille det som @timeMaximum

set @timeSlider='2013-05-10 00:00:00';
set @timeMaximum='2013-05-14 08:35:00';


select if (d.name = 'Free', @timeSlider, b.timeBooked) as free_from,
       if (d.name = 'Free', b.timeBooked, @timeSlider := b.timeBooked + interval b.duration minute) as free_until,
       d.name as Free
from (select 1 as place, 'Free' as name union select 2 as place, 'Booked' as name ) as d 
inner join bookingEvents b 
having free_from < free_until
union select @timeSlider as free_from, @timeMaximum as free_until, 'Free' as Free
from (select 1) as d
where @timeSlider < @timeMaximum

order by free_from, free_until
;
 


  1. PRAGMA table_list i SQLite

  2. FEJL 1215:Kan ikke tilføje fremmednøglebegrænsning ved brug af ON SLET SET NULL

  3. Sådan får du id fra databasen ved klik på listevisningselement i Android

  4. Sådan fjerner du cifre fra slutningen af ​​strengen ved hjælp af SQL