(I do not speak English very well, but I will try)
I have two tables.
table1
id carid user
---------------------
1 | A001 | user1
2 | A002 | user1
3 | A003 | user2
4 | A002 | user3
table2
id carid datetime lat lon
-------------------------------------------------- -
1 | A001 | 2013-25-06 10:00:00 | -23.0000 | -46.0000
2 | A002 | 2013-25-06 10:01:00 | -24.3500 | -45.3200
3 | A002 | 2013-25-06 10:02:00 | -24.3800 | -45.3300
4 | A001 | 2013-25-06 10:05:00 | -23.0500 | -46.1000
5 | A003 | 2013-25-06 10:07:00 | -24.3500 | -45.3200
6 | A001 | 2013-25-06 10:10:00 | -23.0700 | -46.1200
I need to select each individual registry "carid" from "user1" sorted by datetime
Result I need:
carid datetime lat lon
--------------------------------------------------
A001 | 2013-25-06 10:10:00 | -23.0700 | -46.1200
A002 | 2013-25-06 10:02:00 | -24.3800 | -45.3300
The way I actually do this is to select all the "carid" from the user I want, and select each line separately through .net.
`SELECT carid FROM table1 where user = "user1";`
carid
-----
A001
A002
Then select the line I want:
SELECT * FROM table2 WHERE car_id='A001' ORDER BY datetime DESC limit 1 SELECT * FROM table2 WHERE car_id='A002' ORDER BY datetime DESC limit 1
But depending on the number of "carids" registries from this user, I have to make a lot of queries. I don't know if it is possible to do this with a single SELECT that improves Im's performance, but here is what I tried:
SELECT car_id, datetime, lat, lon from table1 INNER JOIN table2 on carid = car_id WHERE user = 'user1' GROUP BY carid ORDER BY datetime DESC;
Result:
carid datetime lat lon
-------------------------------------------------- ----
A002 | 2013-25-06 10:01:00 | -24.3500 | -45.3200
A001 | 2013-25-06 10:02:00 | -23.0000 | -46.0000
And I also tried this:
SELECT car_id, MAX(datetime) as datetime, lat, lon from table1 INNER JOIN table2 on carid = car_id WHERE user = 'user1' GROUP BY carid ORDER BY datetime DESC;
Result:
carid datetime lat lon
-------------------------------------------------- ----
A001 | 2013-25-06 10:10:00 | -23.0000 | -46.0000
A002 | 2013-25-06 10:02:00 | -24.3500 | -45.3200
But the result that I got is wrong. I do not know what to do without highlighting all the lines, which is slower than the way I really do it.
Any thoughts?