从使用相同联接的多个表中进行选择

时间:2013-09-26 19:18:04

标签: mysql sql database

我不确定如何在没有示例的情况下解释我需要做什么,所以我希望我能够很好地解释自己!

假设我的MySQL数据库中有以下表格:

buyers
sellers
adverts
addresses
locations
object_addresses

buyerssellersadverts都是“对象”。它们与addresses object_addresses相关联,object_typeobject_idaddress_id

addresses表格有一个location_id,可以将其与某个位置相关联。

我最终想要的是选择一定距离内的所有类型的物体(使用locations表上的纬度和经度)。

我对距离计算本身没有问题。但是,我无法选择所有“对象”及其各自的地址/位置(因为它们都使用了object_address)。

我能够做到以下几点:

SELECT * FROM buyers as b
INNER JOIN object_addresses as oa on oa.ObjectId = b.Id
INNER JOIN addresses as a on oa.AddressId = a.Id
INNER JOIN locations as l on a.LocationId = l.Id
WHERE oa.ObjectType = 'buyer';

我很难将sellersadverts合并到上面的陈述中。

这可能是一个简单的答案,但我今晚看不到它。有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:1)

SELECT * FROM buyers as b
INNER JOIN object_addresses as oa on oa.ObjectId = b.Id
INNER JOIN addresses as a on oa.AddressId = a.Id
INNER JOIN locations as l on a.LocationId = l.Id
WHERE oa.ObjectType = 'buyer'
union
SELECT * FROM sellers as s
INNER JOIN object_addresses as oa on oa.ObjectId = s.Id
INNER JOIN addresses as a on oa.AddressId = a.Id
INNER JOIN locations as l on a.LocationId = l.Id
WHERE oa.ObjectType = 'seller'

等?

如果你不喜欢它 - 基本上,你需要多次包含地址位 - 这样每个地址位都可以链接到每个对象类型......

答案 1 :(得分:0)

在特定条件oa.ObjectType = 'seller',oa.ObjectType = 'advert',oa.ObjectType = 'buyer'上使用联接尝试此操作,因此只有相关结果集才会加入

SELECT * FROM buyers as b

INNER JOIN object_addresses as oa on (oa.ObjectId = b.Id AND oa.ObjectType = 'buyer')
INNER JOIN advert  as ad on (oa.ObjectId = ad.Id AND oa.ObjectType = 'advert')
INNER JOIN seller  as s on (oa.ObjectId = s.Id AND oa.ObjectType = 'seller')
INNER JOIN addresses as a on oa.AddressId = a.Id
INNER JOIN locations as l on a.LocationId = l.Id

其他解决方案是加入所有表格,然后检查对象类型

SELECT * FROM buyers as b

INNER JOIN object_addresses as oa on (oa.ObjectId = b.Id )
INNER JOIN advert  as ad on (oa.ObjectId = ad.Id )
INNER JOIN seller  as s on (oa.ObjectId = s.Id )
INNER JOIN addresses as a on oa.AddressId = a.Id
INNER JOIN locations as l on a.LocationId = l.Id
WHERE oa.ObjectType IN('buyer' , 'advert' , 'seller')