I have two tables x and y
Table x has 24 columns each of which holds a different Id value
Table Y has an Id value column and a description
I need to write a procedure, query or view that returns the descriptions for each of the 24 Id values contained in table x in the best performing way possible.
I’ve written a view that calls a function 24 times. The function returns the description based on the Id provided.
Whilst this works it doesn’t perform particularly well.
Is there a technique I should use where this number of descriptions are required from a single table?
Here is the definition for table x (with non relevant columns removed for clarity)
[DefinitiveHLATypeId] [int] IDENTITY(1,1) NOT NULL,
[PersonId] [int] NOT NULL,
[A_X] [int] NULL,
[A_Y] [int] NULL,
[B_X] [int] NULL,
[B_Y] [int] NULL,
[Bw_X] [int] NULL,
[Bw_Y] [int] NULL,
[C_X] [int] NULL,
[DRB1_X] [int] NULL,
[DRB1_Y] [int] NULL,
[DRB3_X] [int] NULL,
[DRB3_Y] [int] NULL,
[DRB4_X] [int] NULL,
[DRB4_Y] [int] NULL,
[DRB5_X] [int] NULL,
[DRB5_Y] [int] NULL,
[DQA_X] [int] NULL,
[DQA_Y] [int] NULL,
[DQB_X] [int] NULL,
[DQB_Y] [int] NULL,
[DPA1_X] [int] NULL,
[DPA1_Y] [int] NULL,
[DPB1_X] [int] NULL,
[DPB1_Y] [int] NULL
Here is the definition for table y (with non relevant columns removed for clarity)
[AntigenId] [int] IDENTITY(1,1) NOT NULL,
[AntigenDescription] [varchar](2000) NOT NULL
The relationship between the two tables is between the _X & _Y columns in table x and the AntigenId column in table Y
I need to return the Antigen Description for each of the _X & _Y columns in table x.
Without seeing any sample data in your tables, if you have a table that have 24 columns of data that you need to compare to another table there are a few ways to do this.
First, you could perform multiple joins on the table for each column similar to this:
I don’t know if joining the tables 24 times would be the most efficient, so it might be easier to perform an
UNPIVOTon the table with 24 columns and join on that result:See SQL Fiddle with Demo
The
UNPIVOTis the same as using aUNION ALLontablexto transform the data from multiple columns into rows of data which will make it easier to join on:Based on your edit, your query would be similar to this:
Note: In the long term my suggestion would be to redesign the
tablexbecause having a table structured in this way will make it difficult to access the data.