Skip to main content
Known Participant
March 21, 2010
Question

SQL order by two columns & loop

  • March 21, 2010
  • 2 replies
  • 594 views

+----------+---------+

| Category | id      |

+----------+---------+
| 1        | 70      |

| 1        | 71      |

| 3        | 80      |

| 4        | 73      |

| 5        | 83      |

| 5        | 81      |

| 5        | 69      |

| 4        | 72      |

| 1        | 74      |

| 4        | 82      |

| 3        | 85      |

| 3        | 68      |

| 4        | 88      |

| 6        | 66      |

+----------+---------+

I have the following table, and need a way of producing results which will involve an SQL statement with a loop, but i'm not sure how.

First I want to take out the results in order of category, so 1, 3, 4, 5, 6, and for each of those categories, order the records by id, (category/id  1/70, 1/71, 1/74, 3/68, 3/80, 3/85, 4/72, 4/73, 4/88 etc...).

When there are no more records to show, I want to loop back to the first smallest category and ID number.

How is this possible? Note that the categories do not ascend by +1 every time, so it is not possible to take the previous category number and +1.

Thanks in advance.

Izzy

This topic has been closed for replies.

2 replies

Izzyg33Author
Known Participant
March 21, 2010

Hi David

Thanks for this. I realise that I didn't explain the problem properly at all!

I need just one record from the table so show at a time (its a photo gallery), and the category number has to be the same or higher than the previous (if there is not a higher category number, then start again from the beginning), and the id has to be higher than the previous for that category. Thats where it gets complicated!

I'm passing the previous record's category and id to the next page via appending them to a 'next' button.

Thanks for your help.

Izzy

Participating Frequently
March 23, 2010

Sorry, based on your description, all you need is the order by that David provided. If this is still wrong, please post example data that shows how you would like the data ordered.

David_Powers
Inspiring
March 21, 2010

Not sure what you mean by needing a loop, but you can order the results the way you want very simply:

SELECT Category, id

FROM this_table

ORDER BY Category, id