views:

53

answers:

4

So I have a category table set up. Within this table there is a field called "id", "name","fk_parent_cat_id" (and more). The "fk_parent_cat_id" basically just ties one particular category to a parent category.

Ok. That being said, how would I make a query that grabs the information on the category, but ALSO grabs the information on the parent category. My main concern is that right now I am only grabbing the parent id, which is nice, but I dont want to have to run another query to identify the name of the parent category.

A normal query result would be something like:

id: 2
name: category 1
fk_parent_cat_id: 1

And, I want the result to be

id: 2
name: category 1
fk_parent_cat_id: 1
fk_parent_cat_name: top category

Does this question make sense? I figure there is a way to do this with some sort of join...

Thanks for any inptut!

+3  A: 

You can accomplish this with an INNER JOIN. Just ensure the name of your tables and foreign key columns are what they actually are in your database (since you gave no information regarding the column names in the ParentCategory table). Keep in mind that if you have a single category table (i.e. all of your categories are stored in a single table) that there is nothing wrong with self-joining against the same table - you just need to alias the tables names in your query to ensure they aren't ambiguous.

SELECT
     C.id
,   C.name
,   C.category
,   P.parent_cat_name 
FROM
    ChildCategory C
INNER JOIN
    ParentCategory P
ON
    C.fk_parent_cat_id = P.parent_cat_id
The Lazy DBA
Cool. This should work. It is one single category table btw. I think I need to do some research into all the types of joins that exist. I always sorta had an idea of what they are about, just need to start using them now that I am creating all kinds of relational databases with joining tables and such..
Roeland
A: 

Assuming I understand correctly, this is a basic join

SELECT id, fk_parent_cat_id, fk_parent_cat_name 
FROM table, parent_table 
WHERE table.id = parent_table.id;

Fix the table names with the correct ones since you didn't have them, and this also assumes your primary key in the parent table is just called 'id' as well.

If I'm misunderstanding, correct me in a comment.

Zurahn
+1  A: 

Use a self join in the query.

SELECT t.id, t.name, t.fk_parent_cat_id, p.name fk_parent_cat_name
FROM table t INNER JOIN
table p on t.fk_parent_cat_id = p.id
astander
+1  A: 
SELECT c.id, c.name, c.fk_parent_cat_id, p.name
FROM category c
left outer join category p on c.fk_parent_cat_id = p.id
RedFilter