这有点困难,因为 MySQL 没有 Row_Number() 所以你需要模拟它。一种方法是使用自联接和计数。您也可以使用@rownumber
此处描述的技术
在我的示例中,我使用 animal_id 来查找最近的,但您可能希望将 JOIN 条件更改为 AND t1.born_on < t2.born_on
SELECT farmer_id
FROM
(
SELECT t1.farmer_id,
t1.animal_id,
Count(t2.animal_id) rn,
t1.type
FROM table1 t1
LEFT JOIN table1 t2
ON t1.farmer_id = t2.farmer_id
AND t1.animal_id < t2.animal_id
GROUP BY t1.farmer_id,
t1.animal_id,
t1.type
) as t
WHERE RN < 10
and type = 'Sheep'
HAVING COUNT(animal_id) >= 3
演示
使用的样本数据
| ANIMAL_ID | FARMER_ID | TYPE |
---------------------------------
| 1 | 1 | dog |
| 2 | 1 | dog |
| 3 | 1 | dog |
| 4 | 1 | dog |
| 5 | 1 | dog |
| 6 | 1 | dog |
| 7 | 1 | dog |
| 8 | 1 | dog |
| 9 | 1 | dog |
| 10 | 1 | dog |
| 11 | 2 | dog |
| 12 | 2 | dog |
| 13 | 2 | dog |
| 14 | 2 | dog |
| 15 | 2 | dog |
| 16 | 2 | dog |
| 17 | 2 | sheep |
| 18 | 2 | sheep |
| 19 | 2 | sheep |
| 20 | 3 | sheep |
| 21 | 3 | sheep |
| 22 | 3 | sheep |
| 23 | 3 | cat |
| 24 | 3 | cat |
| 25 | 3 | cat |
| 26 | 3 | cat |
| 27 | 3 | cat |
| 28 | 3 | cat |
| 29 | 3 | cat |
| 30 | 3 | cat |
结果只有 2,因为即使 3 有三只羊,它们也不在最后 10 只