我有一个新的应用程序,我正在试图找出数据。是休闲车广告,我的想法是:
AdID
以及price
等常见项目),如果某个广告与其中一个广告加入,或者以AdID
在我的某个“辅助”广告代码表traveltrailer
或RV
中找到,那么我在网上看到了类似于以下内容:
select
E.EmployeeName, coalesce(s.store,o.office) as Location
from
Employees E
left outer join
Stores S on ...
left outer join
Offices O on ...
问题是旅行预告片和RV表将包含一些在另一个中不存在的独占物品。作为一个简单的例子,表可以像 -
使用上面的left join
方法有时我可能会检索电机列(如果它是RV),有时我可能不会(如果它是旅行预告片)。我无法弄清楚如何做到这一点。
我可以传入一个类型(RV
或TravelTrailer
)并根据类型运行两个不同的查询之一,但我想传入一个AdID
并获取我的信息。我还可以执行两个查询,一个用于使用AdID
获取广告信息,然后根据从广告表返回的类型获得第二个查询。如果可能的话,我想知道如何在一次拉动中做到这一点。
谢谢!
答案 0 :(得分:3)
我会重新考虑您开始存储数据的方式。
将RV表和TravelTrailer表合并如下:
products (product_id, product_type_id, product_attribute, attribute_value)
其中product_type_id引用表product_types上的id :( FK约束)
product_types (id, name)
IE中。你可能有RV是id#1和motor homes id#2。
并且product_attribute_id引用表product_attributes上的id :( FK约束)
product_attributes (id, name)
IE中。你的体重可能是id#1,长度是id#2,睡眠能力是id#3等等。
这样你就不会有表X中的某些产品,表Y中的某些产品,Z中的其他产品等,你可以更正常地编写查询。如果您的查询总是比它们需要的更复杂,那么它通常与设计相关。
答案 1 :(得分:0)
一种方法是:
select
Advertisement.AdId
,Advertisement.Price
,coalesce(Trailer.Length,RV.Length) as Length
,coalesce(Motor,"") as Motor
-- other fields as desired
from Advertisement
left join Trailer on Trailer.AdID = Advertisement.AdId
left join RV on RV.AdID = Advertisement.AdId;