0

我有一个 mysql 查询,它从 2 个表“属性”和“报价”进行交互。

'offers' 表可以匹配属性表中的记录,方法是通过唯一代码或属性所在的县或地区引用特定记录。

这是我的查询示例...

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

在报价表中,有 3 列//the_property对于将适当的报价与属性链接起来至关重要。如果要约适用于整个县,则该字段为空白,否则,如果要约针对特定财产,则此字段包含唯一的财产代码。the_countythe regionthe_property

我认为通过使用多个 JOIN 将是解决方案,但是当 3 个主要offer字段中的任何一个为空时,连接会为offers表字段返回“NULL”。

这个怎么解决??

非常感谢

4

4 回答 4

1

您可以连接两个表并在连接子句或 where 子句中指定额外的连接条件

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
于 2013-07-16T13:11:55.583 回答
0

后面提供的列会覆盖早期的表,您需要给它们起别名:

选择 *,offers.the_property the_property_from_offers,...

于 2013-07-16T13:13:28.323 回答
0

您有三个不同的报价表,它们都具有相同的字段名称。问题是 MySQL 不允许具有相同名称的多个列。

最简单的解决方法是更改​​要oron子句中使用的连接:

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` prop LEFT JOIN
     `offers`
      ON prop.code = offers.the_property or
         (prop.county = offsCnty.the_county and offers.the_property is null) or
         prop.region = offsRgn.the_region
HAVING distance <= 2.5
ORDER BY `sleeps` ASC, `distance` ASC
LIMIT 0, 10;

如果您确实使用了多个连接,那么您应该在select子句中有如下表达式:

select coalesce(offers.code, offsCnty.code, offsRgn.code) as code

对于报价表中的每一列。

于 2013-07-16T13:17:39.797 回答
0

如果您希望最具体的报价优先,我认为您必须这样写:

SELECT prop.*,
       COALESCE(offers.col1, offsCnty.col1, offsRgn.col1) col1,
       COALESCE(offers.col2, offsCnty.col2, offsRgn.col2) col2,
       ...,
       <huge formula> 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
于 2013-07-16T13:18:36.173 回答