I’m having a bit of trouble getting the right results from a query.
At the moment I have two tables, main_cats and products.
The result I am after is 6 records, in date order, with only one unique main_cat_id.
The basic table structures are
- Main_cats: main_cat_id, main_cat_title
- Products: product_id, main_cat_id, product_name, date_added.
I am hitting problems when I join the main_cat table to the products table. It seems to totally ignore the ORDER BY clause.
SELECT date_added, product_name,main_cat_title FROM ic_products p
JOIN ic_main_cats icm on icm.main_cat_id=p.main_cat_id
WHERE p.main_cat_id IN (1,2,12,22,6,8)
GROUP BY p.main_cat_id
ORDER BY date_added ASC
LIMIT 6
If I leave the join out the query works but shows more than one main_cat_id and I cannot display the main_cat_title as needed.
Your question is (at heart) a “select min/max date per group and associated fields” question.
Let me explain: look at this table, being the first
LEFT JOINof the query above:This joins
productsto itself: it produces a table with every combination ofdate_addedpairs within each category, where the date in the first column is always greater than the date in the second.Since this is a left join, when the date in the first column is the smallest for that category, the date in the second will be
NULL.So this basically selects the minimum date for each category (I assume you want the minimum date ie earliest occurence, based off your
ORDER BY date_added ASCin your question — if you wanted the newestdate_addedyou’d change the>to a<in the above join).The second
LEFT JOINtoicmis just the one in your original question, so that we can retrievemain_cat_title.There is no need to
LIMIT 6here because firstly, only one row is retrieved permain_cat_idthanks to the firstLEFT JOIN, and secondly, yourAND p.main_cat_id IN (1,2,12,22,6,8)only selects 6 categories. So 6 categories at one row per category retrieves 6 rows. (Or at most 6; if you have no items in a particular category of course no rows will be retrieved).