我有4张桌子:
订单:
OrderID Detail Discount
------------------------
1001 xxx True
1002 xxx True
1003 xxx True
1004 xxx False
1005 xxx True
1006 xxx True
OrderDiscounts:
OrderID DiscountTypeID DiscountID
----------------------------------
1001 1 8
1002 2 12
1003 1 9
1005 2 13
1006 2 9
优惠券(DiscountTypeID = 1
):
CouponID Title
------------------------
8 CouponTitle8
9 CouponTitle9
广告系列(DiscountTypeID = 2
):
CampaignID Title
--------------------------
9 CampaignTitle9
12 CampaignTitle12
13 CampaignTitle13
我需要一个查询,将所有4个表合并到1个表中,这将产生一些结果,如:
结果:
OrderID Discount DiscountType DiscountTitle
-----------------------------------------------------
1001 True Coupon CouponTitle8
1002 True Campaign CampaignTitle12
1003 True Coupon CouponTitle9
1004 False
1005 True Campaign CampaignTitle13
1006 True Campaign CampaignTitle9
请注意,某些优惠券ID可能作为广告系列ID存在。在这种情况下,像CouponID和CampaignID一样存在'9'。
除了所需的查询之外,在构建查询时如何/为什么使用这些命令的正确解释将是很好的,因为我不只是寻找答案,但我也想自己处理类似的情况。谢谢!
答案 0 :(得分:2)
以下代码应该可以使用 - 我已经用稍加修改完成了:我添加了一个'DiscountType'表。
据我所知,也许您正在寻找的是一个快速简单的答案,但我认为可以更好地设置数据模式。为每种折扣类型设置一个完整的表格是不可扩展的,也不是灵活的,并且随着时间的推移,像建议的那样的查询只会变得更加毛茸茸,更加肮脏和更加苛刻。当然,这一切都取决于您的要求。
SELECT
OrderId = o.OrderId,
Discount = CASE WHEN o.Discount = 1 THEN 'True' ELSE 'False' END,
DiscountType = COALESCE(dt1.DiscountType, dt2.DiscountType, ''),
DiscountTitle = COALESCE(coup.Title, camp.Title, '')
FROM
Orders o
LEFT JOIN
(OrderDiscounts od1
JOIN Coupons coup ON coup.CouponID = od1.DiscountID
LEFT JOIN DiscountType dt1 ON dt1.DiscountTypeId = od1.DiscountTypeId
) ON o.OrderId = od1.OrderId
AND o.Discount = 1
AND od1.DiscountTypeID = 1
LEFT JOIN
(OrderDiscounts od2
JOIN Campaigns camp ON camp.CampaignID = od2.DiscountID
LEFT JOIN DiscountType dt2 ON dt2.DiscountTypeId = od2.DiscountTypeId
) ON
od2.OrderID = o.OrderID
AND o.Discount = 1
AND od2.DiscountTypeID = 2
在SqlFiddle上亲自查看here。
答案 1 :(得分:1)
它应该类似于下面的内容:
SELECT Orders.OrderID,
CASE when OrderDiscounts.OrderID is NULL THEN False ELSE True end,
CASE when OrderDiscounts.DiscountTypeID = 1 THEN 'Coupon'
when OrderDiscounts.DiscountTypeID = 2 THEN 'Campaign'
else '' end,
CASE WHEN OrderDiscounts.DiscountTypeID = 1 THEN Coupons.Title
WHEN OrderDiscounts.DiscountTypeID = 2 THEN Campaigns.Title
ELSE '' end
FROM Orders
LEFT JOIN OrderDiscounts on Orders.OrderID = OrderDiscounts.OrderID
LEFT JOIN Coupons on OrderDiscounts.DiscountID = Coupons.CouponID
LEFT JOIN Campaigns on OrderDiscounts.DiscountID = Campaigns.CampaignID