duanji9677 2013-07-16 13:02
浏览 376
已采纳

MySQL在多列上查询多个JOIN两个表

I have a mysql query which interact from 2 tables, 'properties' and 'offers'.

The 'offers' table has can match a record in the property table by either referring to a specific record by a unique code or by the county or region the property is located.

Here's an example of my query...

SELECT *, ROUND(((3959 * acos(cos(radians(51.1080390)) * cos(radians(latitude)) * cos(radians(longitude) - radians(-4.1610140)) + sin(radians(51.1080390)) * sin( radians(latitude)))) * 2),0)/2 AS `distance`
FROM `properties` AS prop
LEFT JOIN `offers` ON prop.code = offers.the_property
LEFT JOIN `offers` AS offsCnty ON prop.county = offsCnty.the_county
LEFT JOIN `offers` AS offsRgn ON prop.region = offsRgn.the_region
HAVING distance <= 2.5
ORDER BY `sleeps` ASC, `distance` ASC
LIMIT 0, 10

In the offers table the are 3 columns the_property / the_county / the region are crucial for linking the appropriate offer with the property/ies. If an offer is to be applied to the entire county, the field the_property is blank, otherwise if an offer is for a specific property this field contains the unique property code.

I thought that by using multiple JOIN's would be the solution, however when the any of the 3 main offer fields are empty the join returns 'NULL' for the offers table fields.

How can this be resolved??

Many thanks

  • 写回答

4条回答 默认 最新

  • duangai2831 2013-07-16 13:11
    关注

    You can join the two tables and specify your extra join conditions in the join clause or the where clause

    SELECT *, ROUND(((3959 * acos(cos(radians(51.1080390)) * cos(radians(latitude)) * cos(radians(longitude) - radians(-4.1610140)) + sin(radians(51.1080390)) * sin( radians(latitude)))) * 2),0)/2 AS `distance`
    FROM `properties` AS prop
    LEFT JOIN `offers` ON prop.code = offers.the_property 
           OR prop.county = offers.the_county 
           OR prop.region = offers.the_region
    HAVING distance <= 2.5
    ORDER BY `sleeps` ASC, `distance` ASC
    LIMIT 0, 10
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测