开发者

Help with a DB query

So I have a category table set up. Within this tabl开发者_JAVA百科e 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!


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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜