Monday, April 25, 2011

How do I join two tables ON a column, that has the same name in both tables?

see above...

From stackoverflow
  • What you are asking is called NATURAL JOIN in relational terminology. Some database servers support this clause. I would prefer to manually specify the join expression even if the provider supports such a clause like:

    SELECT .... FROM Table1 JOIN Table2 ON Table1.JoinCol = Table2.JoinCol ...
    
    StingyJack : As an addition to your point, I always specify the table or alias for the table so anyone looking will know exactly where the column comes from. It makes refactoring / maintenance much easier later on.
  • Use an Alias for the table names is the shortest.

    SELECT a.*, b.*
    FROM table1 as 'a'
      INNER JOIN table2 as 'b'
        ON a.col1 = b.col1
    

    You can also specify the full table names.

    SELECT table1.*, table2.*
    FROM table1
      INNER JOIN table2 
        ON table1.col1 = table2.col1
    
  • select  *
    from    Table1
            inner join
            Table2
            on Table1.ColumnName = Table2.ColumnName
    

    Simple really.

    StingyJack : With someone who is obviously new, is it a good idea to encourage SELECT * ?
    Garry Shutler : What else can you say without any hint of the schema?
    : I'd suggest "ColumnName" instead of Column, since Column is a keyword. Not that it matters in real SQL, just for example code.
    Garry Shutler : Done. Thought I may as well.
  • And for completeness (depending on your DBMS) you could use "USING":

    SELECT
        ...
    FROM
        table_a
    INNER JOIN
        table_b
    USING
        (common_column);
    

0 comments:

Post a Comment