SQL Server条件连接具有不同的结果列

时间:2014-07-27 17:59:36

标签: sql sql-server join conditional

我有一个新的应用程序,我正在试图找出数据。是休闲车广告,我的想法是:

  • 广告 - 包含AdID以及price等常见项目),
  • RV - 包含房车专用信息,
  • TravelTrailer - 包含旅行预告片信息

如果某个广告与其中一个广告加入,或者以AdID在我的某个“辅助”广告代码表traveltrailerRV中找到,那么我在网上看到了类似于以下内容:

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表将包含一些在另一个中不存在的独占物品。作为一个简单的例子,表可以像 -

  • 预告片 - 长度,睡眠容量
  • RV - 长度,睡眠容量,马达

使用上面的left join方法有时我可能会检索电机列(如果它是RV),有时我可能不会(如果它是旅行预告片)。我无法弄清楚如何做到这一点。

我可以传入一个类型(RVTravelTrailer)并根据类型运行两个不同的查询之一,但我想传入一个AdID并获取我的信息。我还可以执行两个查询,一个用于使用AdID获取广告信息,然后根据从广告表返回的类型获得第二个查询。如果可能的话,我想知道如何在一次拉动中做到这一点。

谢谢!

2 个答案:

答案 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;