Here is my table
+----+---------------+-------+
| id | product name | cat |
+----+---------------+-------+
| 0 | product A | 1 |
| 1 | product B | 2 |
| 2 | product C | 1 |
| 3 | product D | 3 |
+----+---------------+-------+
The output I’m trying to achieve is:
Product A
Product C
Product B
Product D
Here’s the query I’m working with:
SELECT * FROM products GROUP BY cat ORDER BY id ASC
Now I’m very inexperienced with MySQL, and in-short I’m trying to group my results, and order them within their groups.
The above query (verbatim) gives me a syntax error.
After a little research, (seeing some posts with similar problems) I think I may need to use a JOIN to complete this functionality. But I have no idea where to begin with this.
Can anybody help?
Not sure you need grouping here. Try this:
SELECT * from products ORDER BY cat ASC, id ASC
This sorts first by cat and then by id. Note that you should have an index on the cat field to optimize this query (I already assume that id is primary key).