I’m wondering if this its even posible.
I want to join 2 tables based on the data of table 1.
Example table 1 has column food with its data beeing “hotdog”.
And I have a table called hotdog.
IS it possible to do a JOIN like.
SELECT * FROM table1 t join t.food on id = foodid
I know it doesnt work but, its even posible, is there a work arround?.
Thanks in advance.
No, you can’t join to a different table per row in
table1, not even with dynamic SQL as @Cade Roux suggests.You could join to the
hotdogtable for rows where food is ‘hotdog’ and join to other tables for other specific values of food.This requires that you know all the distinct values of food, and that all the respective food tables have compatible columns so you can UNION them together.
What you’re doing is called polymorphic associations. That is, the foreign key in
table1references rows in multiple "parent" tables, depending on the value in another column oftable1. This is a common design mistake of relational database programmers.For alternative solutions, see my answers to:
I also cover solutions for polymorphic associations in my presentation Practical Object Oriented Models In SQL, and in my book SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.