[英]Get last five record form each category
I have 2 tables in mySQL database 我在mySQL数据库中有2个表
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 第一个表是tbl_article_category,它有article_category_id作为主键,第二个tbl_article,它有article_id作为主键,article_category_id作为外键
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 现在我想得到每个类别的最后五个重新编码形式,所以如果我有5个类别我想要从每个类别得到25个重新编码
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. 它使用article_id值查找最后的记录,但您可以使用所需的任何字段对记录进行排序,例如通过DATETIME字段。
Here is an amusing/kludgy way to do this: 这是一个有趣/ kludgy方式来做到这一点:
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. 特别是, join
无法利用索引。 But, for 25 rows, the performance should be fine. 但是,对于25行,性能应该没问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.