I have to build an application on an existing SQL database and I came upon this situation.
There’s a table (call it T1) where several fields reference values from another table (T2), which basically is made up of just 2 fields, Id and Name. As a consequence, T2 holds data of different nature and meaning, because the fields in T1 that relate to it are of very different kinds. (This seems to me an unusual design.)
My question: given this design, how I can build a join query in order to get the value of T2.Name related to each T1 field.
EDIT
I could get what I want by doing one query per field:
SELECT t2.name AS name1
FROM t1
INNER JOIN t2
ON t1.field1 = t2.id;
SELECT t2.name AS name2
FROM t1
INNER JOIN t2
ON t1.field2 = t2.id;
SELECT t2.name AS name3
FROM t1
INNER JOIN t2
ON t1.field3 = t2.id;
But this is nonsense. So how could I pack all this in one single query?
You need to alias references to t2 to get corresponding names:
You might want to replace inner with left joins if foreign keys are nullable.