I have the following table:
id user_id recorded latitude longitude speed note_type details image_url
1 10 3/29/2013 33.77701316 -84.39004377 -1 11 Test 2ecc2e36c3e1a512d349f9b407fb281e-2013-03-29-16-15-..
I am trying to find a way to combine the following queries into one complete query that would give me all records that match each individual query (each of these works fine separately just cant figure out how to combine them):
SELECT id, ( 3959 * acos( cos( radians(User_Input_Longitude) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(User_Input_Latitude) ) + sin( radians(User_Input_Longitude) ) * sin( radians( latitude ) ) ) ) AS distance
FROM note HAVING distance < User_Input_Distance
ORDER BY distance LIMIT 0 , 1000
SELECT details
FROM note
WHERE CHAR_LENGTH(details) > User_Input_CharacterLength
SELECT DISTINCT details
FROM note;
SELECT DISTINCT image_url
FROM note;
So basically I need a query that compares the distance based on the long/lat points to user defined long/lat points and user defined distance, checks the character length of the details field and then finally only records that have distinct data for details and image_urls (alot of the image_urls and details are left empty so I've been using distinct to find only those that actually have data in them not sure if this is proper way to do ti).
Like I said before, each of these queries works individually right now but unfortunately I dont have enough skillz in mySql to combine them in an intelligent way.
Any advice on this would be great.
HAVING distance < User_Input_Distanceshould beWHERE distance < User_Input_Distance, for starters. other than that you need to update with your table schema as you need to perform somejoins, and for that the relationships need to be known.distanceclause, and simply select a (potentially) slightly larger result set for the 'bounding square', then in your PHP reject the results that don't meet the more exact polar coordinates. That way you reduce CPU load, and can also take advantage of indexes on thelongitudeandlatitudecolumns, especially if your table is large. HTHdistancefor every row, since without doing the polar computations it can't know which rows will qualify in the intermediateHAVINGclause. If you make the SELECT based on the 'bounding square', by pre-calculating a max_lat, min_lat, max_lng, min_lng, as a function of 'User_Latitude', 'User_Longitude' and 'User_Distance', then a WHERE clause of(latitude BETWEEN (min_lat AND max_lat))AND(longitude BETWEEN min_lng AND max_lng )would only need to read qualifying rows if latitude and longitude columns were indexed.