Jump to content

Queries within queries


scottybwoy

Recommended Posts

Is it possible to have a query within a query?  Let me expand...

 

I have a table of categories and a table of products that belong to the categories.  In the table of categories there may be child categories.  Usually the parent category doesn't have products in it, but just child categories within the same table.  The structure is like this to keep it simple I will just show the relevant fields :

| categories_id | parent_id |
=====================
| 29                |              |
| 30                | 29          |
| 31                | 30          |
| 32                | 30          |
...

And the other table is just as simple :

| product_id | category_id |
=====================
| 21            | 31             |
| 22            | 32             |
| 23            | 31             |
...

So is it possible to have a single query that can take a category_id, lets say 29 in this example, discover whether it is a parent, if so does its child have a daughter (this loop recursive until the category has no children) Then retrieve all the product_ids for it?

 

Hope that makes sense?

 

Thanks

Link to comment
Share on other sites

Can you not do a recursive function instead?  I imagine it would be more flexible.  So in my example I'm just returning a list of IDs but you get the point..

 

function getChildren(parentID)

{

$sql = "SELECT id FROM categories WHERE parentID='$parentID'";

// loop through results and for each one call:

$allChildren .= "$id,";

$allChildren .= getChildren($id);

return $allChildren;

}

 

$allChildren = getChildren("");

Link to comment
Share on other sites

  • 2 weeks later...
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.