Primary and foreign key

RipIT

Member
Joined
Apr 5, 2010
Messages
5
Programming Experience
Beginner
Hello
I’m trying to understand RDMS a little better. I’d say it’s the primary and foreign keys that seem to be confusing. As an example a very simple example if I want to have a database that has a table for my name and a second table that has the cars I own Then I could have in the first table two fields such as NameID and Name. And the second table has two fields CarsID and cars. So I have more than one car so it’s a one to many relationship. One name and many cars (few cars). To show my name with each car I own on a form I need to relate the tables with a foreign key. The primary keys would be in one table NameID and the other CarsID. So do I need another field in the Name table such as CarsID? Or do I need another field in the Cars table such as NameID?
Something like…

tblName
NameID
Name
CarsID

And …
tblCars
CarsID
Cars

One of the conveniences of .net is after a dataset is made I can just drag it onto a form for either a gridview or details (textboxes and lables).
Do I drag the tblName or the tblCars from the dataset? I guess it depends on what I want to show. I want to show my name with each car. So I assume it’s the tblName portion of the dataset since I would like to show my name with each record with each car I own.

Thanks for any input
 
The NameID would contain an Id representing your Name.
In the Cars table there should also be a NameID field. For each car you own (which would have its own ID) your NameID would be populated.

To find out what cars you have would be something along the lines of:
VB.NET:
SELECT ca.Cars, na.Name 
INNER JOIN tblName na ON na.NameID = ca.NameID 
FROM Cars ca
WHERE na.NameID = 12345
NameID would be a primary key in both tables
 
Back
Top