这个查询试图做一些mysql不容易做的事情,即限制每组的行数。将列表user_id's
传递给查询,并返回一些,但组需要限制为每组 4 行。该查询有效,但根据 Sequel Pro 的说法,200-500 毫秒的速度有点慢。
请在标记前继续阅读!!
SELECT id, user_id, article_id, row_number
FROM (
SELECT a2.id, a2.user_id, a2.post_id,
@num:= if(@group = a2.user_id, @num + 1, 1) as row_number
FROM (
SELECT a1.id, a1.user_id, a1.post_id
FROM articles as a1
WHERE a1.user_id IN (3,14,1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,18,19,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,38,39,13,114,1111,12,223,2234,225,226,227,228,229,2210)
ORDER BY a1.date DESC
) as a2,
(SELECT @num := 0) t
) as f
WHERE row_number <= 4;
这个查询的解释是:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 10516 Using where
2 DERIVED <derived4> system NULL NULL NULL NULL 1
2 DERIVED <derived3> ALL NULL NULL NULL NULL 10516
4 DERIVED NULL NULL NULL NULL NULL NULL NULL No tables used
3 DERIVED s1 ALL Reco... NULL NULL NULL 1180931 Using filesort
我曾考虑将其分解为多个查询,但我似乎仍然遇到将每个组结果限制为 4 个的问题。总而言之,我试图避免大量查询和昂贵的查询。
关于通过将其分解并将其中的一些移动到应用程序中来提高此查询速度的最佳方法的任何想法?