du31992 2010-04-28 03:16 采纳率: 0%
浏览 17

如何组合距离和关键字SQL查询?

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!

  • 写回答

3条回答 默认 最新

  • dsbpaqt61965 2010-04-28 03:20
    关注

    Perhaps instead of using a union, you could run the distance query as a subquery, then SELECT from that (treating it as a temporary table) to get the ones which match the keyword search? In essence, something of the general form...

    SELECT * FROM (SELECT * FROM ... WHERE distance < X) as distResults WHERE ....
    

    Or potentially the other way around - run the keyword search first, then take those results and use them to run the distance search. Whichever way will eliminate the most calculation overhead.

    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题