Question
I am desining a database and got stuck with this issue:
My case is to design an ERD to keep track of the cars and their movements from location to location.
The users utilize a form which contains three fields: The first one is used to enter the car#. The second field is used to enter the location the car came from (From_Location) and the third field is to enter the location the car is going to (To_Location).
For instance, Car#1 is moving from location#A to location#B. Another example, car#2 is moving from location#B to Location#A.
How can I create the location table and connect it to the car table so that it covers From and To ?
The relationship should be many to many.
I hope the problem is clear enough.
Solution
I would have three tables
- Car
- Location
- CarLocation
Car would have the appropriate car information
- CarId
- Name
- Color
- Year
- Make
- Model
Location would be just the one field unless you wanted to add Lat/Long info etc...
- LocationId
- LocationName
- Latitude
- Longitude
CarLocation would include at least four fields
- CarLocationId
- CarId
- FromLocationId
- ToLocationId
I would probably include an UpdateTimestamp field to the CarLocation table.
OTHER TIPS
The relationship between Car and Location is: for every car there are exactly two locations (from and to), and for every location there are 0..n cars.
You should: make Car table with fields: LocationFrom and LocationTo each is a foreign key to table Location which has LocationId and LocationName (you can have only the latter, that's arguable).
Why you don't need third table: The connection isn't many to many - it's two to many.
When you have a true many to many relation the tables can't tell which record in one adresses which record on the other, and hence the need for a third table (try it out.. for example if a you were to save all of each car's locations - that would have been a many to many relation, because now a car is related to 0..n locations, and a location is related to 0..n cars. Now how would you be able to tell which car record is related to which location (you could have n columns for that, but that's unreasonable, so you need another table)) anyhow here you have only two columns in car which are related to location "directly".
Added:
So you need the history as well... In this case you really do need an extra table.
I would have add a column to my original solution so that now table car has columns:
Id, FromLocation, ToLocation, LocationHistoryId
FromLocation and ToLocation remains the same, LocationHistoryId is a foreign key of table LocationHistory which has the following columns:
CarId, LocationId
Where the key is a composite key that includes both fields (and obviously LocationId points to Location table)