Jump to content

MySQL Sub-Queries


AdamB

Recommended Posts

Hello,

Im trying to get my head around several levels of subquerying and its driving me insane, i cant figure this out. This code selects what I need it too, all of the sub-categories within the master category.

[code]SELECT categories_id FROM categories WHERE parent_id = 3[/code]

But when I try to then sub-select the sub-sub-categories contained within these results Im only returned with products that reside in the sub category, not the sub-sub-category.

[code]SELECT products_id FROM products WHERE master_categories_id IN (SELECT categories_id FROM categories WHERE parent_id = 3)[/code]

Am I going about this totally the wrong way, or is there something simple Ive forgotten? Thanks for any help!!
Link to comment
Share on other sites

If you are using PHP or some other language to retrieve the categories, then you may want to try using the approach linked to below as well.

Using the second code snippet you'd change "array((int)$section)" to "array((int)$parentid_variable)"
http://www.phpfreaks.com/forums/index.php/topic,112054.msg454856.html#msg454856

[quote author=fenway link=topic=123849.msg514297#msg514297 date=1169843317]
So you want all of the categories to each product? How many can there be? Which way do yo uwant to go?
[/quote]
[quote author=AdamB link=topic=123849.msg514302#msg514302 date=1169843444]
I know what the Master Category ID is, I just need to select all of the products residing in the "Sub Category" and "SubSubCategory"...
[/quote]

I don't know if the "..." in your previous post means that the sub categories are unlimited but what's being asked for is the limit, if any, to the number of subcategories that you allow or are looking to retrieve. An appropriate JOIN can then be constructed to retrieve the ids.

The following article should make things clearer and also show another approach for storing the data.
http://dev.mysql.com/tech-resources/articles/hierarchical-data.html
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.