I have a SQL database with two tables.
A sessions
table containing:
- session id: the primary key
- login timestamp: the unix timestamp of the start of the session
- logout timestamp: the unix timestamp of the end of the session
- user id of the logged user
An events
table containing:
- event id: the primary key
- event timestamp: the unix timestamp of the event
- action id: the type of event occurred
An event may occurs during a user's session, or it may occur while no one is logged in. In the described scenario only one user can be logged at a time.
I need to get the list of events occurred during each user session so I need a way to link each event to a session, whether the event occurred during a session.
As a first solution I thought of including a nullable foreign key in the events
table referring to a session. In this case, if an event occurs without a user being logged in the FK key will be NULL, otherwise it will contain the session id.
But with this solution there is a data consistency problem: it would be possible to create an event linked to a session and give it a timestamp that is not between the start and end timestamps of the associated session. This is not desired since the event may relate to a session having a time window that does not include the event time itself.
A second solution would be not to use the FK described and to retrieve the data by means of a query that takes into account the start and end timestamps of each session and returns for each event the id of the session to which the event belongs.
The final question is whether the choice of not using an FK makes sense for this scenario or violates the principles of good database design, and if such a technique can lead to performance problems in data retrieval since the conceptual relation between sessions and events don't rely on FKs.
Aucun commentaire:
Enregistrer un commentaire