I happen to have a table with n records ... 20 for example ... Of those 20, 5 records belong to 4 people, that is to say that there are 4 people who were registered 5 times in that table, for a total of 20 (by way of example) ... The query that I must obtain is only 4 records, and correspond to the last reigstro of each person, taking into account that this table has a column start date where the value of the date varies in ascending order. I have the following sql code:
SELECT * FROM MYTABLA T1 WHERE T1.fechainicio=(SELECT MAX(fechainicio) FROM MYTABLA WHERE idpersona=T1.idpersona)
As you can see, I do 2 things (select's) to the same table .. Is there any way to improve that query? Well there will be thousands of records ... In addition to that I also do JOINS to other 3 tables ..
Editing my question for a better explanation ....
The first SELECT with the JOINs makes everything perfect, obtaining a result like this: It generates a result of 9 records, the table has 10 but there is a user who is 2 times and only brings the last one of that user ...
On the other hand, the query that @LCC gives me generates all 10 records like this:
I understand that using subqueries within the where slows the query, but I do not know how to remove that subquery from the where in such a way that I keep bringing the same results I need (the last of each user), and thus optimize the query.