[Solved] most efficient way to write this sql query?


This is a little more difficult because MySQL doesn’t have Row_Number() so you’ll need to simulate it. One way is use a self join and a count. You could also use the @rownumber technique described here

In my example I used animal_id to find the most recent but you may want to change the JOIN condition to 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

DEMO

SAMPLE Data used

| 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 |

The result is only 2 because even though 3 has three sheep they weren’t in the last 10

solved most efficient way to write this sql query?