简体   繁体   中英

Join 2 tables based on column name present in a table row

I have a table called Target where I have 5 columns:

ProductLevel
ProductName
CustomerLevel
CustomerName
Target

In another table called Products I have 3 columns:

ProductId
ProductCategory
ProductBrand

In the 3rd table called Customer I have 3 columns:

CustomerID
CustomerName
SubCustomerName

Is there a way to do a dynamic join where I select the column I will use in the JOIN based on the value that I have in the 1st table?

Example: If in the first table I have Category in ProductLevel, I'll join the table product using ProductCategory field. If I have Brand, I'll join using ProductBrand... The same happens with Customer table.

PS: I'm looking for a way to create it dynamically in a way I can add new columns to that tables without changing my code, then in the future I can have ProductSegment column in Product Table and Segment as a value in ProductLevel in Target table.

Yes, like this:

SELECT * FROM
  Target t
  INNER JOIN
  Product p
  ON
    (t.ProductLevel = 'Category' AND t.??? = p.ProductCategory)
    OR
    (t.ProductLevel = 'Brand' AND t.??? = p.ProductBrand)

You didn't say which column in Target holds your product category/brand hence the ??? in the query above. Replace ??? with something sensible

PS; you can't do as you ask in your PS, and even this structure above is an indicator that your data model is broken. You can at least put the code in for it now even if there are no rows with t.ProductLevel = 'Segment'

Don't expect this to perform well or scale.. You might be able to improve performance by doing it as a set of UNION queries rather than OR, but you may run into issues where indexes aren't used, crippling performance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM