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
https://forums.phpfreaks.com/topic/70332-query-help/
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
https://forums.phpfreaks.com/topic/70332-query-help/#findComment-353308
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.