By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,413 Members | 1,594 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,413 IT Pros & Developers. It's quick & easy.

Questions about Foreign Keys

P: 47
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)

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.
Jul 9 '09 #1
Share this Question
Share on Google+
3 Replies


ck9663
Expert 2.5K+
P: 2,878
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
Jul 9 '09 #2

P: 10
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
Jul 16 '09 #3

P: 47
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
Jul 23 '09 #4

Post your reply

Sign in to post your reply or Sign up for a free account.