I have 3 tables I'm joining together to get what users are in a specific area. A scaled back example of the tables:
USER Table (stores all user information)
ID | Name
----------
1 John
2 Joe
3 Mike
GEO (has all geo location info; including latitude and longitude; which im excluding for the example )
ID | CITY
-------------
1 | ORLANDO
2 | MIAMI
3 | DAYTONA
LOCATIONS (stores each users location; each user has multiple locations)
ID | AREA (id = user.id, geo = geo.id)
--------
1 | 1
1 | 2
1 | 3
2 | 1
3 | 1
3 | 3
I've created a function in php to pull the results for a given LAT / LONG withing a certain radius like so (excluding the whole function as its not relevant):
select USER.ID as USERID, (6371 * acos(cos(radians( {$lat})) * cos(radians(g.latitude)) * cos(radians(g.longitude) - radians({$long})) + sin(radians({$lat})) * sin(radians(g.latitude)))) AS distance
from
GEO G
join LOCATIONS LOC on LOC.AREA = G.ID
join USER U on LOC.ID = USERID
HAVING distance <= {$radius}
Now the issue. This works and pulls all the info, but results in showing the same user multiple times due to the user being in the LOCATIONS table multiple times (ie shows 100 results, with 15 different users)
So my thought was to GROUP BY USER.id; however this only matches the first location for that user; only resulting in 2 results.
I've tried DISTINCT; but the rows are not distinct as the user.id or location.id are a different combo for each row.
I've also tried working backwards with sub queries
SELECT * from USER where id = (
select id from GEO where area = (
select id, (long trig here) as distance) from GEO)
but that wont work as I have to select the trig statement as distance so I can't just just select the id from the GEO table
I'm at my wits end trying to get unique users; but still have it search in all the user locations. I know I could loop the results in php and rebuild them; however this query easily returns thousands of result since each users location is shown in the results and I'd rather not do that for speed purposes.
Any help in the right direction would be much appreciated..
ADDITION
to elaborate the result issue a tad, if you ran this query on ORLANDO with a radius that would extend to DAYTONA, if a user was in DAYTONA you'd get
USER | CITY
-----------
1 | ORLAND
1 | DAYTONA
2 | ORLANDO
3 | ORLANDO
3 | DAYTONA
which results in duplicates of user 1 & 3
but when you group by user.id you only get
USER | CITY
-----------
2 | ORLANDO
which drops user 1 & 3 since when its grouped it only shows their area as DAYTONA