I have 2 tables in mySQL database
First table is tbl_article_category which has article_category_id as primary key and the second tbl_article and it has article_id as primary and article_category_id as foreign key
now I want to get the last Five recode form each category so if i have 5 categories i want to get 25 recodes last five from each one
do you have any thought to get this recodes
You can try this query -
SELECT * FROM (
SELECT a1.*, COUNT(*) cnt FROM tbl_article a1
LEFT JOIN tbl_article a2
ON a1.article_category_id = a2.article_category_id AND a2.article_id <= a1.article_id
GROUP BY
a1.article_category_id, c1.article_id
) t
WHERE cnt <= 5;
It finds last records using article_id values, but you may sort records using any field you need, eg by DATETIME field.
Here is an amusing/kludgy way to do this:
select ac.category_id, a.*
from (select category_id,
substring_index(group_concat(ac.article_id order by ac.article_category_id desc),
',', 5) as last5
from tbl_article_category ac
group by category_id
) c5 join
article a
on find_in_set(a.article_id, last5) > 0
order by 1;
Note: this does not have performance in mind. In particular, the join
cannot take advantage of indexes. But, for 25 rows, the performance should be fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.