MySQL如何按每个分类查询10条数据,这是做网站开发中通常会遇到的问题。实现方法很多,今天直接上干货,也不做过多的解释,了解就好。表结构如下图:
具体sql语句如下:
SELECT id,category_id,title,keywords,description,view,download,size,prefer,price,page,preview,image,type,t,file,search FROM ( SELECT id,category_id,title,keywords,description,view,download,size,prefer,price,page,preview,image,type,t,file,search, @row_num := IF(@prev_category = category_id, @row_num + 1, 1) AS row_number, @prev_category := category_id FROM content, (SELECT @row_num := 0, @prev_category := NULL) r ORDER BY category_id asc, id asc ) AS ranked_results WHERE row_number <= 10;
更高效的语句如下:
SELECT c.* FROM content as c JOIN (SELECT id, @row_num := IF(@prev_category = category_id, @row_num + 1, 1) AS row_number, @prev_category := category_id FROM content, (SELECT @row_num := 0, @prev_category := NULL) r ORDER BY category_id ASC, id ASC ) AS ranked_results ON c.id = ranked_results.id WHERE row_number <= 10;