MySQL - Pre-ordering joined content?

Soldato
Joined
15 Jan 2004
Posts
10,185
Code:
SELECT stuff
FROM products
LEFT JOIN items ON items.product_id = products.product_id
WHERE products.category_id = '1'
GROUP BY products.name
ORDER BY products.name

Now of course I am grouping to only select 1 row from "items", but how do I pre-order the "items" table.
 
Soldato
OP
Joined
15 Jan 2004
Posts
10,185
Here's the 2 tables, and the query result.

K7rW5Pd.jpg.png

Using group, it's obviously selecting one (the first) row from "items" for each row of "products".

However, what would I do if I wanted it to arrange the "item", so instead of just grabbing the first associated row from "items", I could order it by value. Example below is ordering with the lowest value:

6GIDjGM.jpg.png
 
Last edited:
Associate
Joined
4 Jan 2010
Posts
603
You could use the Min function if you want to return the lowest value in a group. Caveat, I normally write Microsoft SQL but Google says that the Min function works in mySQL too.
 
Associate
Joined
14 Oct 2004
Posts
979
Use a subquery in the join and order there.

SELECT stuff
FROM products
LEFT JOIN (select * from items order by value asc) items ON items.product_id = products.product_id
WHERE products.category_id = '1'
GROUP BY products.name
ORDER BY products.name
 
Back
Top Bottom