Log in

View Full Version : ordering (group by)



d-machine
02-07-2014, 05:50 AM
I have a table named, "myorder".
I want to select the information from it as described on the image below:
Increasing id, and grouping the same product_ids together.

5344

My sql command didn't work out:


SELECT f.*
FROM myorder f
INNER JOIN (SELECT product_id, MAX(id) AS Ordered GROUP BY product_id) o
ON f.product_id = o.product_id
ORDER BY o.Ordered

traq
02-07-2014, 06:19 AM
GROUP BY is an aggregate modifier - it produces a single row and value for all of the rows it groups (typically, an average).

What you're describing is simply sorting twice.
SELECT ...
ORDER BY f.product_id, o.Ordered;

If you need more help, please share your table schemas.

d-machine
02-07-2014, 07:30 AM
Can you please write the full code? (assuming my table is exactly as described on the image).

traq
02-07-2014, 05:27 PM
Your table is not described "exactly" in the image you posted. Please show your table schema (both tables, unless you are joining to itself) and describe which columns you actually want. (You can use SHOW CREATE TABLE `your_table_name_here` to get the schema information.)

d-machine
02-12-2014, 01:44 AM
Here is the table myorder from the database:
5367
What I want is to print the table using the following method (on this image I havn't mentioned the other columns, but they are also necessary:
5368

traq
02-12-2014, 07:11 AM
Okay - I misunderstood how you wanted to sort these. What I suggested (ORDER BY col1, col2) only uses col2 as a tie breaker. I would recommend using a stored procedure to do this, or simply performing the second sort in your application (it would be trivial to do so while retrieving the results, for example). I'm not sure there is a single-query way to get the rows in the order you want, but I'll do a bit more research.

d-machine
02-12-2014, 07:41 AM
I really appreciate if you could help me to write a procedure or queries for that! thanks in advance