I have the following MySQL query:
SELECT *
FROM products
WHERE catalog = 1
GROUP BY style
ORDER BY name ASC
limit 0, 100
Since I have multiple products with the same “style”, this will return information about whatever the first product that has a certain “style” (through the GROUP BY condition).
Because some products have a “discount”, my question is as follows: HOW do I make it so that the “GROUP BY style” condition gives first priority to a product that has a discount? My ultimate goal is to use 1 query instead of after that going through each returned style and checking if there is any products with a discount
If I specify “GROUP BY style, discount”, it returns 2 products with the same style: 1 with and 1 without a discount. This is NOT something that I need — I need to return only 1 match (unique) style but give preference to those items that match this style that have a discount.
You cannot impose priority within groupped set in a single query. You can restrict your results by using WHERE before applying GROUP BY, but that will just strip your result of rows not satisfying WHERE condition. To find order within groupped sets use a query like this: (assuming id is the primary key here)