Reputation: 83
While designing a relational database I got the questoin in my head if the design I made could be made easier. The design consists of 4 tables: (simplified)
PK = primary key,
FK = foreign key
Lets say we want to get details about a location. If the location is a school we want to see the name, amount of students and the name of the group of schools its part of. If it is a office we only want to see the name of the office. With the current design this is impossible to do in 1 query (with my knowledge).
question: Is there a better way to design this database so I can get the needed details about a location in 1 query.
Although there may be a way to get these details in 1 query I am more interested in enhancing the database design.
Thanks in advance, Knarfi
ANSWER: I finally found the term that describes my problem: Polymorphic Association. Especially this question gave me a good answer.
Upvotes: 0
Views: 610
Reputation: 452
You can merge School and Office to one Entity, say: Organization with the following attributes:
About your last question: "Although there may be a way to get these details in 1 query I am more interested in enhancing the database design." I must say that this is not a design question but an implementation one. Remember that it is a very bad practice to change your design according to your implementation needs...
In any case you can use ONE query in both cases (yours and mine) see other people answers. tIp: try to use views... they are usefull in such cases.
Upvotes: 1
Reputation: 108400
The database design doesn't restrict a location
from having both a school
and office
related to it at the same time. (Could be multiple school and/or multiple office.)
There's several possible ways to retrieve information related to location
.
Here's one approach:
SELECT 'school' AS source
, s.name
, s.students
, g.name AS school_group_name
FROM location sl
JOIN school s
ON s.location_id = sl.id
LEFT
JOIN group_of_schools g
ON g.id = s.group_id
UNION ALL
SELECT 'office' AS source
, o.name
, NULL
, NULL
FROM location ol
JOIN office o
ON o.location_id = ol.id
If you need to restrict to a specific set of location, you'd need to add WHERE
clause on each SELECT
.
Add an ORDER BY
if you want the rows returned in a particular order.
Upvotes: 1
Reputation: 44
You can try something like this
SELECT location.*,school.*,office.*
FROM location
LEFT JOIN school ON school.locationID=location.locationID
LEFT JOIN office ON office.locationID=location.locationID
In result you will have NULL values for school fields if there will be office and vice versa. But you have to check this in your application and make decision there - database sends you all data.
Upvotes: 1