Php 他数到四以上
没有经过这样的测试Php 他数到四以上,php,mysql,optimization,query-optimization,greatest-n-per-group,Php,Mysql,Optimization,Query Optimization,Greatest N Per Group,没有经过这样的测试 SELECT a1.id, a1.user_id, a1.post_id, COUNT(a1_plus.id) AS other_count FROM articles as a1 INNER JOIN articles a1_plus ON a1.user_id = a1_plus.user_id AND a1.date <= a1_plus.date WHERE a1.user_id IN (3,14,1,2,3,4,5,6,7,8,9,10,11,12,14,15
SELECT a1.id, a1.user_id, a1.post_id, COUNT(a1_plus.id) AS other_count
FROM articles as a1
INNER JOIN articles a1_plus
ON a1.user_id = a1_plus.user_id
AND a1.date <= a1_plus.date
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)
GROUP BY a1.id, a1.user_id, a1.post_id
HAVING other_count <= 4
选择a1.id、a1.user\u id、a1.post\u id、COUNT(a1\u plus.id)作为其他\u计数
从文章中选择a1
内部连接条款a1_plus
在a1.user\U id=a1\U+1.user\U id上
a1.date可能重复的@MarcB您立即标记了这一点,但它不是重复的,我正在寻找另一种解决方案,以替代Baron Schwartz提供的答案。如果可能的话,我希望将繁重的工作从查询中转移到应用程序中。您想根据什么进行分组?您是否正在尝试获取每个用户最近4篇文章的列表?@noz:查询有点奇怪,非常奇怪。问题中的查询不起作用(文章id未定义)。解释涉及到另一个查询(s1来自哪里?)。注意:此查询的结果集与OP问题中查询的结果集明显不同。这是非常明显的-因此在开始时有“一点假设”。
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
SELECT a.id
, a.user_id
, a.post_id
FROM articles a
WHERE a.user_id IN (3,14,1,2,3,4,5,6,7,8,9,10,11,12,...)
ORDER BY a.date DESC
@group = a2.user_id
Date user id Date user id
---------- ------ -- ---------- ------ --
2103-07-22 abc 1 2103-07-22 abc 1
2103-07-22 abc 2 2103-07-22 abc 2
2103-07-22 abc 3 2103-07-22 abc 3
2103-07-22 EFGHI 4 2103-07-22 abc 5
2103-07-22 abc 5 2103-07-22 abc 6
2103-07-22 abc 6 2103-07-22 abc 7
2103-07-22 abc 7 2103-07-22 EFGHI 4
7 rows selected. 5 rows selected.
SET @gr=0, @row=0;
SELECT
id,user_id,post_id,row_number
FROM
(SELECT
id,
user_id,
post_id,
@row:=if(user_id <> @gr, 0, @row + 1) as row_number,
@gr:=user_id
FROM
articles
WHERE
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 user_id , date DESC) as a1
WHERE
row_number < 4
SELECT a1.id, a1.user_id, a1.post_id, COUNT(a1_plus.id) AS other_count
FROM articles as a1
INNER JOIN articles a1_plus
ON a1.user_id = a1_plus.user_id
AND a1.date <= a1_plus.date
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)
GROUP BY a1.id, a1.user_id, a1.post_id
HAVING other_count <= 4