MySQL: group by consecutive days and count groups

前端 未结 5 1738
广开言路
广开言路 2020-12-17 20:43

I have a database table which holds each user\'s checkins in cities. I need to know how many days a user has been in a city, and then, how many visits a user has made to a c

5条回答
  •  无人及你
    2020-12-17 21:45

    I think you should consider changing database structure. You could add table visits and visit_id into your checkins table. Each time you want to register new checkin you check if there is any checkin a day back. If yes then you add a new checkin with visit_id from yesterday's checkin. If not then you add new visit to visits and new checkin with new visit_id.

    Then you could get you data in one query with something like that: SELECT COUNT(id) AS number_of_days, COUNT(DISTINCT visit_id) number_of_visits FROM checkin GROUP BY user, city

    It's not very optimal but still better than doing anything with current structure and it will work. Also if results can be separate queries it will work very fast.

    But of course drawbacks are you will need to change database structure, do some more scripting and convert current data to new structure (i.e. you will need to add visit_id to current data).

提交回复
热议问题