MySQL Query to find users still inside room

时间:2016-02-12 19:53:51

标签: mysql sql database

Below is my database table, where I will have Check In and Check Out entry records for attending the conference room.

id  registration_id roomno day type
1   101             1      2   In
2   103             1      2   In
3   101             1      2   Out
4   105             1      2   In
5   103             1      2   Out
6   101             1      2   In
7   103             1      2   In
8   101             1      2   Out
9   105             1      2   In
10  103             1      2   Out

Now, I want to select those records, which are still attending the conference. Condition is like their last record should be type = In. There can be multiple In/Out entries for each user during a day.

Please let me know the quickest possible MySQL query.

Thanks

Answer which I ended up using:

select * from `registrations_inouts` t 
group by t.registration_id 
having max(id) = max(case when type = 'In' then id end) 
order by rand() limit 1; 

1 个答案:

答案 0 :(得分:3)

Here is one method using not exists:

select *
from t
where t.type = 'In' and
      not exists (select 1
                  from t t2
                  where t2.registration_id = t.registration_id and t2.type = 'Out'
                 );

Another method uses conditional aggregation:

select t.registration_id
from t
group by t.registration_id
having max(id) = max(case when type = 'In' then id end);

Note: both of these assume that the ids are assigned sequentially in time, so larger ids are later in time.