SQL查询组合

时间:2013-09-21 06:44:47

标签: mysql 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

`。我完全糊涂了..请任何人帮助我..

1 个答案:

答案 0 :(得分: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