[英]Join 2 tables based on column name present in a table row
我有一個名為Target的表,其中有5列:
ProductLevel
ProductName
CustomerLevel
CustomerName
Target
在另一個名為Products的表中,我有3列:
ProductId
ProductCategory
ProductBrand
在稱為客戶的第三張表中,我有3列:
CustomerID
CustomerName
SubCustomerName
有沒有一種方法可以進行動態聯接,因此我可以根據第一張表中的值選擇要在JOIN中使用的列?
示例:如果在第一個表中我在ProductLevel中具有Category,那么我將使用ProductCategory字段加入表產品。 如果我有品牌,我將使用ProductBrand加入... Customer表也是如此。
PS:我正在尋找一種動態創建方式,可以在不更改代碼的情況下向表中添加新列,然后在將來我可以在Product Table和Segment中將ProductSegment列作為Target中ProductLevel的值表。
是的,像這樣:
SELECT * FROM
Target t
INNER JOIN
Product p
ON
(t.ProductLevel = 'Category' AND t.??? = p.ProductCategory)
OR
(t.ProductLevel = 'Brand' AND t.??? = p.ProductBrand)
您沒有說Target的哪一欄包含您的產品類別/品牌,因此? 在上面的查詢中。 替換??? 明智的
PS; 您無法按照PS中的要求進行操作,甚至上面的這種結構也表明您的數據模型已損壞。 即使沒有t.ProductLevel ='Segment'的行,您至少也可以立即為其添加代碼
不要指望它能很好地執行或擴展。您可能可以通過將其作為一組UNION查詢而不是OR來提高性能,但是您可能會遇到未使用索引的問題,從而降低了性能
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.