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 > Need sql query to sort mysql results on multiple fields

LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Registered User
Join Date: May 2010
Location: Hyderabd
Posts: 14
Need sql query to sort mysql results on multiple fields

I need a sql query to sort the results from a sql table.

The actual structure of table is like

Table name : categories

catid parentid catname level


1 0 services 1

2 1 printing 2

3 1 cabling 2

4 0 Products 1

5 4 switches 2

6 4 cables 2

7 1 lubricating 2

Now I want to sort the above results grouped by parentid including parent category and then by catname in alphabetical order. Can some one suggest me the best way to do this using sql query.

I want the results to be sorted in the following format

4 0 Products 1
6 4 cables 2
5 4 switches 2
1 0 services 1
3 1 cabling 2
7 1 lubricating 2
2 1 printing 2

Products and services are level 1 categories and others are sub categories. Now I grouped subcategories along with parent category and sorted level 1 categories in alphabetical order and then sorted sub categories in alphabetical order.

Last edited by vibhavram; 02-05-13 at 03:42. Reason: typographic mistakes found
Reply With Quote
  #2 (permalink)  
Registered User
Join Date: Feb 2008
Location: Japan
Posts: 3,437
From the provided sample data, max level might be two.
If this guess was right,
the following query might be an answer...
 FROM  categories AS c
       categories AS p
  ON   p.catid = COALESCE( NULLIF(c.parentid , 0) , c.catid )
     , c.level
     , c.catname
If the max level was not clear,
loop or recursive query might be neccesary to find the catname of the level 1 categories.

Last edited by tonkuma; 02-09-13 at 14:22.
Reply With Quote

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