3

I am trying to combine two (possibly more) tables that has different column names but the same data within the columns I am trying to line up. For example, I have a table called dbo.member and within this table is a column called UID. On another table called dbo.tasklist_data, there is a column called TaskID which holds some of the same data as UID. What I am looking for is to combine the two tables with the result giving me ONLY the UID's on the member table, that matches up with the data in the TaskID column on the tasklist_data table.

I do hope I explained that well enough. Please bear with me as I am new to this but eager to learn. Any help or advice will be greatly appreciated. Thank you.

5

From a high level, you'd simply do this:

SELECT *
FROM dbo.member m
    INNER JOIN dbo.tasklist_data tld ON m.UID = tld.TaskID;

The INNER JOIN will take rows from dbo.member where the UID column values match values contained in the TaskID column from the tasklist_data table. If you wanted ALL the rows from dbo.member, and only matching rows from dbo.tasklist_data, you'd rewrite that as:

SELECT *
FROM dbo.member m
    LEFT JOIN dbo.tasklist_data tld ON m.UID = tld.TaskID;

Steve Stedman has an excellent resource for understanding how the different types of JOIN statements work.

If you need to do this on more than two tables, you simply add JOIN clauses as necessary:

SELECT *
FROM dbo.member m
    INNER JOIN dbo.tasklist_data tld ON m.UID = tld.TaskID
    INNER JOIN dbo.some_other_table sot ON m.UID = sot.some_column_name;

I have broken a (arguably) cardinal sin above by using SELECT * to return all columns from all of the tables mentioned in the FROM clause of the query. It is generally considered good practice to explicitly specify the columns required, for instance:

SELECT m.UID
    , m.SomeColumn1
    , m.SomeColumn2
    , tld.TaskID
    , tld.SomeColumn3
FROM dbo.member m
    INNER JOIN dbo.tasklist_data tld ON m.UID = tld.TaskID;
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.