2013-09-21 120 views
0

我有兩個SQL查詢那些被以下SQL查詢組合

1)SELECT a.* FROM modzzz_listing_main as a LEFT JOIN modzzz_listing_rating as b ON a.id=b.gal_id WHERE LTRIM(a.city) = 'Houston' AND a.state = 'TX' AND a.tags LIKE '%Barber Shop%' ORDER BY b.gal_rating_sum DESC LIMIT 0 ,10

2)SELECT zip_code ,(3959 * acos(cos(radians('41.97734070')) * cos(radians(latitude)) * cos(radians(longitude) - radians('-70.97234344')) + sin(radians('41.97734070')) * sin(radians(latitude)))) AS distance FROM city_finder WHERE latitude IS NOT NULL AND longitude IS NOT NULL HAVING distance < 20 ORDER BY distance ASC

我怎樣才能由條件`

modzzz_listing_main結合這兩個查詢.zip = city_finder.zip_code

'。我是完全confused..please任何一個可以幫助我..

回答

1

看到加入更容易:

select * from 
(
SELECT a.* FROM modzzz_listing_main as a LEFT JOIN modzzz_listing_rating as b ON a.id=b.gal_id WHERE LTRIM(a.city) = 'Houston' AND a.state = 'TX' AND a.tags LIKE '%Barber Shop%' ORDER BY b.gal_rating_sum DESC LIMIT 0 ,10 
) queryA 
left join 
(
SELECT zip_code ,(3959 * acos(cos(radians('41.97734070')) * cos(radians(latitude)) * cos(radians(longitude) - radians('-70.97234344')) + sin(radians('41.97734070')) * sin(radians(latitude)))) AS distance FROM city_finder WHERE latitude IS NOT NULL AND longitude IS NOT NULL HAVING distance < 20 ORDER BY distance ASC 
) queryB 
on queryA.zip=queryB.zip_code 

正確的格式

SELECT * 
FROM 
    (SELECT a.* 
    FROM modzzz_listing_main AS a 
    LEFT JOIN modzzz_listing_rating AS b ON a.id=b.gal_id 
    WHERE LTRIM(a.city) = 'Houston' 
    AND a.state = 'TX' 
    AND a.tags LIKE '%Barber Shop%' 
    ORDER BY b.gal_rating_sum DESC LIMIT 0 , 
             10) queryA 
LEFT JOIN 
    (SELECT zip_code , 
      (3959 * acos(cos(radians('41.97734070')) * cos(radians(latitude)) * cos(radians(longitude) - radians('-70.97234344')) + sin(radians('41.97734070')) * sin(radians(latitude)))) AS distance 
    FROM city_finder 
    WHERE latitude IS NOT NULL 
    AND longitude IS NOT NULL HAVING distance < 20 
    ORDER BY distance ASC) queryB ON queryA.zip=queryB.zip_code 
+0

你toooooooooooooooo輝煌.... 。:) – Preethy

+1

其實它非常基本:)給查詢別名用作虛擬表,並加入它們 – AdrianBR