If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Category table recurssion

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 01-13-10, 10:57
moazam moazam is offline
Registered User
 
Join Date: Jan 2010
Posts: 4
Category table recurssion

Hi,
I have following table structure

Create table categories (
cat_id Int UNSIGNED NOT NULL AUTO_INCREMENT,
parent_id Int UNSIGNED,
cat_name Varchar(50) NOT NULL,
Primary Key (cat_id)) ENGINE = InnoDB;

and I have 16 categories and 360 subcategories. On a single page I am retrieving all categories and subcategories and this requires 16 queries. Is there anyway to do this in one or two queries?

Thanks
Reply With Quote
  #2 (permalink)  
Old 01-13-10, 12:14
dgreenhouse dgreenhouse is offline
Registered User
 
Join Date: Mar 2009
Posts: 11
Read up on "self joins": Join (SQL) - Wikipedia, the free encyclopedia)

You'll want to create a regular index on parent_id also.
Reply With Quote
  #3 (permalink)  
Old 01-13-10, 12:22
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,525
this article will help -- Categories and Subcategories
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #4 (permalink)  
Old 01-13-10, 12:38
moazam moazam is offline
Registered User
 
Join Date: Jan 2010
Posts: 4
Quote:
Originally Posted by r937 View Post
this article will help -- Categories and Subcategories
thanks, i am going to check this now. I have one more question about indexing for instance I am running this query

SELECT field1, field2, field3 FROM aTable WHERE field4=10

My question is should I create index only on field4 or all 4 fields? and what if I add ORDER BY field5 how indexing will work for this?

Thanks
Reply With Quote
  #5 (permalink)  
Old 01-13-10, 13:01
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,525
Quote:
Originally Posted by moazam View Post
My question is should I create index only on field4 or all 4 fields?
just field4

the ORDER BY will require a temporary file anyway

questions like this are always difficult to answer without accurate counts of the number of rows involved

my advice is to learn how to interpret EXPLAIN resaults
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On