How to express in a MySQL query: “get all new elements but at least N elements”.
I’ll try to explain better. I want to know how to make a query if I have a product list [product, price, date, new] and I want to show the user all new elements, but if there are less than N elements (e.g. 5) show also the last items. If could think in a query like:
SELECT * FROM `products` WHERE new='1' ORDER BY date DESC
but this just returns all new elements and this:
SELECT * FROM `products` WHERE new='0' ORDER BY date DESC LIMIT 5
just returns the minimum elements required.
Some examples:
- If the table contains 4 new items, the query should return 4 new items and the latest non-new item
- If the table contains 7 new items, the query should return just the 7 new items
- If the table contains 1 new item, the query should return the new item and 4 non-new items.
Use UNION to combine two result sets.
Note that this assumes that there is a unique key defined on any column or combination of columns in your table (for example, if your table has a primary key this should work).