Connecting Tech Pros Worldwide Help | Site Map

Questions about Foreign Keys

Member
 
Join Date: Mar 2009
Posts: 44
#1: Jul 9 '09
first of all, these are my first steps into SQL world so please dont shoot me.

I have looked around to find answers to the following questions but had no luck so far:

When querying a table with a foreign key, will its linked data also be shown?
if not, how could i adjust that query to show its matching row of the other table?

I am trying to make a forum (just for fun and learning) and have a database like the following (really simple)

Quote:
table Subforum
(PK) ID int
Title varchar(150)
Description varchar(150)

table Topics
(PK) ID int
(FK -> (table Subforum) ID) Subforum_ID int
title varchar(150)

table Posts
(PK) ID int
(FK -> (table Topics) ID) Topic_ID int
Title varchar(150)
Body varchar(MAX)
(FK -> (table Users) ID) User_ID int

table Users
(PK) ID int
Username varchar(50)
Password varchar(MAX)
i hope you can understand and give me some hints/tips on how to go on with my project. At this moment im doubting whether to use Foreign Keys and just query everything.
Im using C# ASP.NET 3.5, if you need to know anything more i will answer as soon as i can.
ck9663's Avatar
Expert
 
Join Date: Jun 2007
Posts: 1,925
#2: Jul 9 '09

re: Questions about Foreign Keys


The foreign key constraint refers to maintaining the relationship of the table. So that you don't insert a row on the child table with a key not existing on the parent table. But the table is still stored and accessed separately. Depending on your need, you can either create a stored proc, function or views to have your desired rowset returned to your app.

In either case, explore the world of JOINS. It will help you linked those tables together and return it as if it's a single row.

Good luck!!!

--- CK
Newbie
 
Join Date: Jul 2009
Posts: 9
#3: Jul 16 '09

re: Questions about Foreign Keys


Its simple..as suggested by ck9663 you need to explore worl of joins.
You can say foreign keys are used to maintaine the relationships of tables.
You can use this

SELECT POSTS.*,TOPICS.*,SUBFORUM.*,USERS.* from
POSTS INNER JOIN TOPICS ON POSTS.TOPIC_ID=TOPICS.ID
INNER JOIN USERS ON POSTS.USER_ID=USERS.ID
INNER JOIN SUBFORUM ON TOPICS.SUBFORUM_ID=SUBFORUM.ID

Insted of stars (*) you can select your desired column in this query.
Use SqlServer query builder and paste this query, it will show you the complete diagram, which would be easy to understand.
HAPPY QUERY..
-Pankaj Tambe
Member
 
Join Date: Mar 2009
Posts: 44
#4: Jul 23 '09

re: Questions about Foreign Keys


Thanks for your reactions, using Pankajs query i was able to crop some queries together.
i just pasted the entire thing and slimmed it down till i got what i needed, i cant write joins just yet, but i am capable of manipulating it
Reply