我有一个mysql查询,可以从2个表,'properties'和'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_county
/ the region
对于将相应商品与商品/商家相关联至关重要。如果要将报价应用于整个县,则字段the_property
为空白,否则如果报价针对特定属性,则此字段包含唯一的属性代码。
我认为通过使用多个JOIN将是解决方案,但是当3个主offer
字段中的任何一个为空时,连接将为offers
表字段返回'NULL'。
如何解决?
非常感谢
答案 0 :(得分:1)
您可以加入这两个表,并在join子句或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
答案 1 :(得分:0)
以后提供的表格会覆盖之前的表格,您需要为它们添加别名:
SELECT *,offers.the_property the_property_from_offers,...
答案 2 :(得分:0)
您有三个不同的商品表,所有商品都具有相同的字段名称。问题是MySQL不允许多个具有相同名称的列。
最简单的解决方法是更改联接以在or
子句中使用on
:
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
对于商品表中的每一列。
答案 3 :(得分: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