-
1 Attachment(s)
ordering (group by)
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.
Attachment 5344
My sql command didn't work out:
PHP Code:
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
-
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.
Code:
SELECT ...
ORDER BY f.product_id, o.Ordered;
If you need more help, please share your table schemas.
-
Can you please write the full code? (assuming my table is exactly as described on the image).
-
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.)
-
2 Attachment(s)
Here is the table myorder from the database:
Attachment 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:
Attachment 5368
-
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.
-
I really appreciate if you could help me to write a procedure or queries for that! thanks in advance