Skip to content
Advertisement

MySQL request for combining and searching in 2 tables

I have 2 tables. One of my tables with users is:

I’m using SQL to detect nearby people: SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(-122) ) + sin( radians(37) ) * sin(radians(latitude)) ) ) AS distance FROMusersHAVING distance < 50 ORDER BY distance DESC LIMIT 20

The other matches is like this:

Where sender is the person who sent the invitation receiver is the person who receives is.

The SQL request should search in users for near by people and check in the matches for their ids. If the ids are not there as sender & receiver return the userID of the person to make a new connection.

For example Paul is searching for nearby people and Dave as we see from users is nearby him. So Dave ID should be returned to Paul ONLY , if their ids are not in matches table OR Paul == receiver AND status == 0.

How this SQL Query should be written to return 20 Ids of the nearby people ?

Advertisement

Answer

I change the distance formula to something that works since mysql 5.7. You didn’t_ specify your database or presented a fiddle example to show your system, so i selected 5.7 as mini9mum and it works also in 8.0 as you see in the fiddle.

the inner query needs two things the user id who searches and his position, because he is excluded from the results and of course to calculate the distance.

The result from the query is checked in the where clause-I hope i got the right idea, so you should check that

✓

✓
✓

✓
id | distance
:- | -------:
id |            distance
:- | ------------------:
6  | 0.09663995445895139
7  | 0.14732089261518266

db<>fiddle here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement