mysqlsqlselectnatural-join

Natural Join in MySQL with matching columns


What if I have two tables with primary key joins, i.e. both columns have same name and same data, and, then I have a column name timestamp, which has same name for both tables but different data according to their tables. Could I still use NATURAL JOIN? or is there a workaround considering I need to use SELECT * from both tables without aliasing?


Solution

  • Don't use NATURAL JOIN! It is an abomination. It does not even take properly declared foreign key relationships into account.

    You may find the USING clause useful:

    select . . .
    from a join
         b
         using (pk);
    

    Another problem with NATURAL JOIN is that the join keys are not listed. This can make it really hard to debug code, if something goes wrong. You are experiencing the problem with the TIMESTAMP column.

    If you do use USING you can use SELECT * and the USING keys appear only once in the SELECT. Sometimes, this can be a convenience.