MySQL:将两个查询组合成一行结果

时间:2012-10-19 06:27:41

标签: mysql sql join

查询的第一部分:

SET @centerLat = '48.531157';
SET @centerLng = '-123.782959';

SELECT user_id, lat, lng, ( 3959 * acos( cos( radians( @centerLat ) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(@centerLng) ) + sin( radians( @centerLat ) ) * sin( radians( lat ) ) ) ) AS distance FROM bid_userloc HAVING distance < 25 ORDER BY distance LIMIT 0 , 20

第二个方面是取user_id并从USERS表中获取大量信息

我还在学习JOIN甚至意味着什么,我不太明白它是如何最好的...

3 个答案:

答案 0 :(得分:0)

你可以试试这个

  SELECT user_id, lat, lng, ( 3959 * acos( cos( radians( @centerLat ) )
  * cos( radians( lat ) ) * cos( radians( lng ) - radians(@centerLng) )
   + sin( radians( @centerLat ) ) * sin( radians( lat ) ) ) ) 
   AS distance,columnsfromuserstable FROM bid_userloc bid
   inner join users us on bid.user_id=us.user_id 
    HAVING distance < 25
   ORDER BY distance LIMIT 0 , 20

答案 1 :(得分:0)

您可以尝试这样的事情:

select * from users where user_id in (select user_id from(

SELECT user_id, lat, lng, ( 3959 * acos( cos( radians( @centerLat ) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(@centerLng) ) + sin( radians( @centerLat ) ) * sin( radians( lat ) ) ) ) AS distance FROM bid_userloc HAVING distance < 25 ORDER BY distance LIMIT 0 , 20

));

答案 2 :(得分:0)

变种与JOIN -

SET @centerLat = '48.531157';
SET @centerLng = '-123.782959';

SELECT
  t1.user_id, t1.lat, t1.lng,
  (3959 * ACOS(COS(RADIANS(@centerLat)) * COS(RADIANS(t1.lat)) * COS(RADIANS(t1.lng) - RADIANS(@centerLng)) + SIN(RADIANS(@centerLat)) * SIN(RADIANS(t1.lat)))) distance,
  t2.*
FROM
  bid_userloc t1
JOIN users t2
  ON t1.user_id = t2.user_id
HAVING
  distance < 25
ORDER BY
  distance
LIMIT
  0, 20;