We start with two tables:
Aminales: ID_animal, nombre, especie, incenter
1 Toby 2 1
2 Micke 2 1
3 Jake 2 1
4 Tom 2 1
Entradas: ID_entrada, ID_animal, municipio
1 1 Las Rosas
2 2 Coslada
3 3 Las Rosas
4 4 Madrid
5 3 Coslada
6 2 Coslada
What I need is to get the amount of animals that are inside the center at present ( incenter=1
) and are dogs (2) for each municipality. As seen in the tables, the animal 3 Jake has been delivered to the animal center twice, ID_entrada
3 and 5. But we only need the lowest ID_entrada
so that this only appears as delivered from its original municipality, in this case Las Rosas
. It does not matter how many times you have entered from other municipalities after being adopted and returned to the center.
The result of the query should be:
Madrid: Tom (total 1)
Las Rosas: Toby, Jake (total 2)
Coalada: Micke (total 1)
I've tried with this query:
SELECT animales.nombre, animales.ID_animal, entradas.ID_entrada
FROM animales
left JOIN entradas ON (animales.ID_animal = entradas.ID_animal AND incenter=1 AND especie=2 AND entradas.ID_entrada=(select min(ID_entrada) from entradas where municipio=$ID_municipio)
I can not make it work. Can you think of something?