如何在派生表概念中转换此查询

时间:2017-01-25 07:18:49

标签: mysql distance latitude-longitude

已更新:

如何在派生表中引入以下查询

(3959 * acos(cos(弧度(36.247137))* cos(弧度(cmlat))* cos(弧度(cmlng) - 弧度(-115.221032))+ sin(弧度(36.247137))* sin(弧度(cmlat))))AS距离

在这个MySql查询中:

MySql查询:

SELECT ( 3959 * acos( cos( radians(36.247137) ) * cos( radians( `cm`.`lat` ) ) * cos( radians(`cm`.`lng` ) - radians(-115.221032) ) + sin( radians(36.247137) ) * sin( radians( `cm`.`lat` ) ) ) ) AS distance, min(pl.price_pure) as minPrice, max(pl.price_pure) as maxPrice, min(pl.`squarefeet_pure`) as minSquare, max(pl.`squarefeet_pure`) as maxsquare FROM  `plans` pl INNER JOIN property pr ON pr.id = pl.property_id INNER JOIN communities cm ON cm.id = pr.community_id Having distance < 20 order by pl.price_pure, pl.squarefeet_pure

............................................ ..............................

上一个查询标题是: 为什么在MySql查询中应用Max,MIN价格公式时没有结果

详细问题:

http://pastebin.com/UR48mbtq这是我的mysql查询..我想获得距离不到20英里的房屋的最高和最低价格..但结果为空。示例中的距离是20但我也导致我的数据库有20英里而不到20英里

MySql查询:

SELECT ( 3959 * acos( cos( radians(36.247137) ) * cos( radians( `cm`.`lat` ) ) * cos( radians(`cm`.`lng` ) - radians(-115.221032) ) + sin( radians(36.247137) ) * sin( radians( `cm`.`lat` ) ) ) ) AS distance, min(pl.price_pure) as minPrice, max(pl.price_pure) as maxPrice, min(pl.`squarefeet_pure`) as minSquare, max(pl.`squarefeet_pure`) as maxsquare FROM  `plans` pl INNER JOIN property pr ON pr.id = pl.property_id INNER JOIN communities cm ON cm.id = pr.community_id Having distance < 20 order by pl.price_pure, pl.squarefeet_pure

使用此结果:

distance              minPrice   maxPrice   minSquare   maxsquare
1754.3401139613718       0       21000003     0            8607

但是当我添加Having子句时,结果为null,并带有以下查询

SELECT ( 3959 * acos( cos( radians(36.247137) ) * cos( radians( `cm`.`lat` ) ) * cos( radians(`cm`.`lng` ) - radians(-115.221032) ) + sin( radians(36.247137) ) * sin( radians( `cm`.`lat` ) ) ) ) AS distance, (pl.price_pure) as minPrice, (pl.price_pure) as maxPrice, (pl.`squarefeet_pure`) as minSquare, (pl.`squarefeet_pure`) as maxsquare FROM  `plans` pl INNER JOIN property pr ON pr.id = pl.property_id INNER JOIN communities cm ON cm.id = pr.community_id Having distance < 20 order by pl.price_pure, pl.squarefeet_pure

更新 如果我从查询中删除max,min公式,那么它给我400结果..

2 个答案:

答案 0 :(得分:1)

Having是在生成查询行后应用的子句。由于您的查询中有聚合函数,但没有GROUP BY,因此mysql为您提供单个(样本)distance结果,然后是整个数据集的最小值和最大值。

之后,应用having子句 - 正如@krishnpatel指出的那样,1754&lt; 20是假的,所以行被丢弃而你没有任何东西。

在您的选择中添加GROUP BY,相当于您的distance计算,以返回您要查找的结果。

答案 1 :(得分:0)

首先收集20英里范围内的物业ID。

然后将其用作子查询,并将JOIN用于主表以完成其余工作:

SELECT MIN(...), ...
    FROM ( SELECT id FROM tbl WHERE ... < 20 ) AS x
    JOIN tbl ON x.id = tbl.id;

HAVING,没有GROUP BY(除非我遗漏了某些内容)。