Search code examples
mysqldatabasedatabase-designentity-relationship

MySQL How To Retrieve Table Name As A Field


Im not sure how to exactly word my issue but I will try my best. Im trying to model a database for a driving school. I have a "timeslot" table such that activities such as lessons, tests, and registration interviews can all be linked to a given timeslot for a staff member. One of the queries I am providing is to be able to view a "timetable" of events for a staff member. I have constructed the query and it is working, however it joins data from various other tables, and I would like to see the names of those tables to know what activity the timeslot is reserved for.

ER Model

The query I perform to check the staff timetable is the following:

SELECT Timeslot.*
FROM Timeslot
LEFT JOIN Test
ON Timeslot.Timeslot_ID = Test.Timeslot
LEFT JOIN Interview
ON Timeslot.Timeslot_ID = Interview.Timeslot
LEFT JOIN Lesson
ON Timeslot.Timeslot_ID = Lesson.Timeslot
WHERE Timeslot.Date BETWEEN CURDATE() AND (CURDATE() + INTERVAL 7 DAY)
AND Timeslot.Staff = 1;

This works and shows a list of all registered timeslots for a given staff member for the next week. What I would like is a further column which would show what type of activity it is, such as "Lesson", "Interview", or "Test". As you can see, I am currently storing this as a field in the timeslot table, which means that I have to specify this every time I insert a timeslot. I will be normalising the database to 3NF and want to avoid duplication. Is there a way I model this to get the name of the table, I considered using UNIONS and many other things but could use some help.

Many thanks and apologies if this seems a bit vague. Mike


Solution

  • My stab at it, if you're keeping the model you've described, would be with a Case statement, like so:

    Select Timeslot.*,
        Case
            When Test.Timeslot Is Not Null Then 'Test'
            When Interview.Timeslot Is Not Null Then 'Interview'
            When Lesson.Timeslot Is Not Null Then 'Lesson'
        End As ActivityType
    From ...
    

    Your query would then have an "ActivityType" column at the very end that you could use.