I have the following query which is working:
$query = "SELECT
a.student_name,
city,
state,
request_date,
lat,
lng,
(3959 * acos(
cos( radians('".mysql_real_escape_string($center_lat)."') )
* cos( radians( lat ) )
* cos( radians( lng ) - radians('".mysql_real_escape_string($center_lng)."') )
+ sin( radians('".mysql_real_escape_string($center_lat)."') )
* sin( radians( lat ) )
)
) AS distance
FROM lesson_requests a
INNER JOIN (
SELECT student_name, MAX(request_date) AS MaxRequestDate
FROM lesson_requests
WHERE (
3959 * acos(
cos( radians('".mysql_real_escape_string($center_lat)."') )
* cos( radians( lat ) )
* cos( radians( lng )
- radians('".mysql_real_escape_string($center_lng)."') )
+ sin( radians('".mysql_real_escape_string($center_lat)."') )
* sin( radians( lat ) ) )
) < ".mysql_real_escape_string($radius)."
GROUP BY student_name
) b
ON a.student_name = b.student_name
AND a.request_date = b.MaxRequestDate
HAVING distance < ".mysql_real_escape_string($radius)."
ORDER BY distance
LIMIT 0 , 10";
What i am trying to do is join in another table to the query called ‘vendor’. That table has a value called ‘user_purchased’ and as one of the filters at the end of the complete query I have to make sure that ‘user_purchased’ from the table named ‘vendor’ does not contain the words ‘abc_company’. using MATCH like this
...AND NOT MATCH(user_purchased) AGAINST ('abc_company')
Could someone help me with the join of this additional table?
Thanks in advance!
There’s a lot going on there…
First, HAVING should only be used with a corresponding GROUP BY. Your GROUP BY applies to the sub query (think of it as a table). I think you want a WHERE clause there.
The self-join (*lesson_requests INNER JOIN (SELECT stuff from lesson_requests*) is kinda confusing too though I can see what you’re trying to do (namely, get the record per student with the max request date).
Finally, a varchar like “name” usually makes for a bad Primary Key. Consider creating some sort of integer student ID surrogate key and using that instead.
Regardless, I think you want something like:
This joins in the vendor table as an OPTIONAL table and assumes that user_purchased in the vendor table corresponds to the student_name. If that assumption doesn’t apply, you need to figure out how vendor and lesson_requests is related and do the join using those columns.
This will still print out a record if a given student_name never appears in the vendor table (because, obviously a student that IS NOT a vendor CAN NOT be the vendor ‘abc_company’)