Grouping MySQL Query Results

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Shiriah
    New Member
    • Jul 2007
    • 2

    Grouping MySQL Query Results

    I feel that this is a rather trivial concept that I cannot quite wrap my head around to make work in PHP. I consider myself an intermediate user in SQL (both MSSQL and MySQL) and somewhat novice in PHP, but I am well versed in programming in general between multiple languages (VB/Java/Python/ColdFusion). By saying this, I'm letting you know not to be afraid to use complex terminology / concepts.

    Here is what I am attempting to do:

    I have a query that is returning a moderate result set. One of the columns of the query, is a category. The results would look like this:
    _______________ ___
    |Category 1 | Object 1|
    |Category 1 | Object 2|
    |Category 1 | Object 3|
    |Category 2 | Object 1|
    |Category 2 | Object 2|
    |Category 3 | Object 3|

    I wish to have my results print out like this:

    Category 1
    - Object 1
    - Object 2
    - Object 3

    Category 2
    - Object 1
    - Object 2
    - Object 3

    The problem with this is, all of my results are coming out of one query, and I don't see a real need to run multiple queries. Maybe it is just my lack of sleep last night that is preventing me from seeing the obvious answer, but this just has my brain locked up trying to figure a simple way to do this.

    This pseudo-code is the only way i've thought to do this so far, but it seems quite over-the-top to me to accomplish something so simple.

    Query all of the categories ( SELECT category FROM table GROUP BY category )
    Loop over the individual categories
    - Print the category heading
    - Run a query selecting all objects with that category ( SELECT * FROM table WHERE category = '$categoryVaria ble' )
    Loop over that query
    - Print the current object
  • pbmods
    Recognized Expert Expert
    • Apr 2007
    • 5821

    #2
    Heya, Shiriah. Welcome to TSDN!

    Have a look at this thread.

    Comment

    • Shiriah
      New Member
      • Jul 2007
      • 2

      #3
      Ah, thank you very much - this is exactly what I was looking for. I tried searching through posts but apparently I did not come up with the right combination of words to turn up this thread.

      I appreciate the quick response and the kindness in pointing me the right direction without calling me a noob! :)

      Comment

      • pbmods
        Recognized Expert Expert
        • Apr 2007
        • 5821

        #4
        Heya, Shiriah.

        Glad to hear you found what you were looking for! Good luck with your project, and if you ever need anything, post back anytime :)

        Comment

        Working...