Jump to content

Query help


tibberous

Recommended Posts

I have a table called categories, it holds categories and subcategories, but they only go one level deep (a subcategory can not be a parent)

 

ID Name Parent

1 A main category 0

2 Another main category 0

3 A subcategory 1

4 A subcategory 2

 

Now, I have another table with items. Those items have a category id.

 

I am trying to search those items by main and subcategories. Search by subcategories is easy, but to search by main category requires searching all of its subcategories.

 

Is there a way I can do this with subqueries or joins, or some other neat bit of mySQL trickery? I used to know subqueries, and somehow forgot them and just started using more lines of PHP and more simple queries.

 

Does anyone know how to do this?

 

Thanks,

 

Trent

Link to comment
Share on other sites

Ok, assuming the following table structure:

 

Table: categories

 

id|          name           |pid

--------------------------

1|First Category          | 0

2|Second Category      | 0

3|First Sub Category    | 1

4|Second Sub Category| 1

 

Table: items

 

id|name|cid

-------------

0|item 1|1

1|item 2|3

2|item 3|2

3|item 4|4

 

The following query should get all of the item where their cid is 1, OR where there cid is a sub category of category 1:

SELECT `id`,`item`,`cid` FROM `items` WHERE `cid`= 1 OR `cid` IN (SELECT `id` FROM `categories` WHERE `pid`=1)

 

 

 

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.