I have 2 tables, one has the categories within it, and the other has the distinct items in it.
What I want to do is to select the item_id and cat_id, and limit it to 5 result for each category, for example:
cat_id item_id
1 1
1 2
1 3
1 4
2 5
2 6
3 7
etc... The closest query i've come up with
SELECT cat.cat_id, cat.cat_name, item_id, item_author, item_name, item_pic_big
FROM item_table ipt
JOIN cat_table cat ON ipt.cat_id = cat.cat_id
GROUP BY item_id
HAVING COUNT(*) < 5
ORDER BY cat.cat_id
That's what I found on stackoverflow, however if I want to change the count to let's say... 2, it gives me the same result, and if I change t开发者_StackOverflowhe group by to cat_id, it only gives me 1 result.
Any help would be appreciated
What you actually need is something like:
SELECT
cat.cat_id, cat.cat_name, item_id, item_author, item_name, item_pic_big
FROM item_table a
JOIN cat_table b ON a.cat_id = b.cat_id
WHERE a.item_id IN (SELECT item_id
FROM item_table
WHERE cat_id = b.cat_id
LIMIT 5)
GROUP BY a.item_id
ORDER BY b.cat_id
Unfortunately, if you try to run this you will get this disappointing error message:
This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
So you'll need a workaround. You can see a list of possible workarounds here: http://www.artfulsoftware.com/infotree/queries.php#104
EDIT: The first solution there can be translated to your structure like this: (I don't have your tables, so there may be minor column names issues)
SELECT temp2.cat_id, temp2.item_id,
temp2.cat_name, temp2.item_author,
temp2.item_name, temp2.item_pic_big
FROM
(SELECT
temp.cat_id,
temp.item_id,
temp.cat_name,
temp.item_author,
temp.item_name,
temp.item_pic_big,
IF( @prev <> temp.cat_id, @rownum := 1, @rownum := @rownum+1 ) AS rank,
@prev := temp.cat_id
FROM (SELECT
a.item_id,
b.cat_id,
b.cat_name,
a.item_author,
a.item_name,
a.item_pic_big
FROM item_table a
JOIN cat_table b ON a.cat_id = b.cat_id
ORDER BY cat_id, item_id) AS temp
JOIN (SELECT @rownum := NULL, @prev := 0) AS r
ORDER BY temp.cat_id, temp.item_id) as temp2
WHERE temp2.rank <= 5
ORDER BY temp2.cat_id, temp2.item_id;
精彩评论