2017-04-21 42 views
0

MySQL查询内的选择数据:MySQL的百公里

select pet_info.pet_user_id as userid, 
pet_info.pet_cat,pet_info.pet_breed as petbreed, 
lostpets.pet_reward,lostpets.currency,pet_info.pet_name as name, 
lostpets.pet_lost_date as date, 
lostpets.pet_city,lostpets.petid as pid, 
lostpets.id as lid,lostpets.type,lostpets.pet_lost_location,lostpets.pet_lost_address,lostpets.pet_postal,lostpets.pet_country 
,(6371 * ACOS(COS(RADIANS('23.0862143')) * COS(RADIANS( `pet_lat`)) * COS(RADIANS( `pet_long`) - RADIANS('72.59330969999996')) + SIN(RADIANS('23.0862143')) * SIN(RADIANS( `pet_lat`)))) AS `distance` 
from lostpets as lostpets 
LEFT JOIN pet_info as pet_info ON lostpets.petid=pet_info.id 
where lostpets.active='Active' AND `distance` < 100 order by `distance` asc 

该查询由两个lat和长之间显示距离。但我想选择100公里范围内的数据。我该如何做到这一点,请帮助我。

+0

添加别名到距离计算等''''AS distance'''',然后在其中子句添加''''与距离<100'''。 –

+0

'where子句'中的未知列'distance' –

回答

0

尝试这种情况:

SELECT 
    pet_info.pet_user_id as userid, 
    pet_info.pet_cat, 
    pet_info.pet_breed as petbreed, 
    lostpets.pet_reward, 
    lostpets.currency, 
    pet_info.pet_name as name, 
    lostpets.pet_lost_date as date, 
    lostpets.pet_city, 
    lostpets.petid as pid, 
    lostpets.id as lid, 
    lostpets.type, 
    lostpets.pet_lost_location, 
    lostpets.pet_lost_address, 
    lostpets.pet_postal, 
    lostpets.pet_country, 
    (6371 * ACOS(COS(RADIANS('23.0862143')) * COS(RADIANS( `pet_lat`)) * COS(RADIANS( `pet_long`) - RADIANS('72.59330969999996')) + SIN(RADIANS('23.0862143')) * SIN(RADIANS( `pet_lat`)))) AS `distance` 
FROM lostpets as lostpets 
LEFT JOIN pet_info as pet_info 
ON lostpets.petid = pet_info.id 
HAVING `distance` < 100 
WHERE lostpets.active = 'Active' 
ORDER BY `distance` asc 
+0

'where子句'中的未知列'distance' –

+0

查看更新的答案。我添加了一个_having_子句,并将_distance <100_移到了where的位置。如果它不能按原样工作,您可能必须将having子句移到where之后。 –