Search code examples
sqlsql-serverjoinsql-server-2014

SQL Server: convenient way to join many tables with same ID?


I have many tables, such as Customer-Age, Customer-Street,..., Customer-OtherField. I want to get them easily to one table, such that Customer-Age-Street-... - OtherField. I have currently used:

SELECT a.Customer, a.Age, b.Street,..., x.OtherField
FROM table1 a, table2 b,..., tableX x
WHERE a.Customer=b.Customer =c.Customer=d.Customer =... =x.Customer`.

I want to get simpler, more convenient way to join the tables with common identifier, Customer.

How to join conveniently many tables with common identifier in SQL Server 2014?


Solution

  • The way you're doing it now is the most "convenient", but it's not optimal and can cause you headaches down the road. Too easy to accidentally do a cross join and it clutters up your WHERE clause with a bunch of unnecessary conditions.

    A better choice is to use the JOIN ON syntax:

    SELECT a.Customer, a.Age,b.Street,...,x.OtherField
    FROM 
    table1 a 
    INNER JOIN table2 b ON a.Customer = b.Customer
    INNER JOIN table3 c ON b.Customer = c.Customer
    INNER JOIN tableX x on c.Customer = x.Customer
    

    This cleans up your code and makes it easier to tell what you are joining on, rather than having to figure out which WHERE clause statements are being used to join tables and which are restricting the query results. It's not any more annoying to type either, you're just putting all those letters in a different place.