How to combine a Distance and Keyword SQL query?
Posted
by Jason
on Stack Overflow
See other posts from Stack Overflow
or by Jason
Published on 2010-04-28T03:16:29Z
Indexed on
2010/04/28
3:23 UTC
Read the original article
Hit count: 343
Hi Folks,
I have a tables in my database called "points" and "category". A user will input info into both a location input and a keyword input text box.
Then I want to find points in my table where the keyword matches either the "title" field in the points table, or the "category" but are within a certain distance from the user's location. I want to order the results by distance.
Here are the 2 queries which btoh work independently:
$mysql = "SELECT *, ( 3959 * acos( cos( radians('$search_lat') ) * cos( radians( lat ) ) * cos( radians( longi ) - radians('$search_lng') ) + sin( radians('$search_lat') ) * sin( radians( lat ) ) ) ) AS distance FROM points HAVING distance < '$radius'";
$mysql2 = "SELECT * FROM `points` LEFT JOIN category USING ( category_id ) WHERE (point_title LIKE '%$esc_catsearch%' OR category.title LIKE '%$esc_catsearch%')";
Here is what I tried:
$sql_search = sprintf("SELECT *,point_id FROM points WHERE point_title LIKE '%%%s%%' UNION SELECT *, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( longi ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM points HAVING distance < '%s' ORDER BY distance LIMIT %d , %d",
$esc_catsearch,
mysql_real_escape_string($search_lat),
mysql_real_escape_string($search_lng),
mysql_real_escape_string($search_lat),
mysql_real_escape_string($radius),
$offset,
$rowsPerPage);
But it tells me there is no know column "distance". If I remove the "Order By" phrase then it works but I'm still not sure this is giving me the results I want. I also tried the query the other way around with the distance search first but that seems to ignore my keyword.
Any thoughts would be much appreciated!
© Stack Overflow or respective owner