Merging tables with unique ID

Viewed 26

I have two temp tables.

Table 1 contains all the string info

ID | string1 | string2 | etc...

Table 2 contains of the int values

ID | int1 | int2 | etc...

They both share a unique ID.

I need to join them so that it first shows all the the info from table 1 and WHEN there is a matching ID in table 2 to add those values to the end of the table, otherwise when table 2 does not contain that ID to put in a 0, There is never a case when table 1 does not have the ID that is in Table 2

So when the ID is in table 2

ID | String1 | String2 | int1 | int2 |

AND when the ID is not in Table 2

ID | String1 | String2 | 0 | 0 |
1 Answers

When you need all rows from left table use LEFT JOIN and for controlling value of table2 use ISNULL function.

Select t1.ID, t1.string1, t1.string2, ISNULL(t2.int1, 0) int1, ISNULL(t2.int2, 0) int2
FROM [table 1] t1
     LEFT JOIN [table 2] t2 ON t1.ID = t2.ID

Also it is not called merging tables, but joining.

Related