What type of JOIN to use

前端 未结 2 1462
后悔当初
后悔当初 2020-12-12 08:17

What type of JOIN would I use to get table1 and table2 to be matched only once. For example, I have table1 (40 rows) and table2<

相关标签:
2条回答
  • 2020-12-12 08:33

    Obviously, you have duplicate values for both of the joining columns. Instead of the Cartesian product an [INNER] JOIN would produce for this, you want each row to be used only once. You can achieve this by adding a row number (rn) per duplicate and join on rn additionally.

    Each table can have more or fewer dupes for the same value than the other unless you have additional restrictions in place (like a FK constraint) - but there is nothing in your question. To keep all rows one would use a FULL [OUTER] JOIN. But you want to keep 10000 records in the result, which is the cardinality of table2. So it must be a LEFT [OUTER] JOIN on table1 (with 40 rows) - and exclude possible excessive rows from table1.

    SELECT t1."LocationArea", t2."Location"
    FROM  (
       SELECT "Location"
            , row_number() OVER (PARTITION BY "Location") AS rn
       FROM   table2
       ) t2
    LEFT JOIN (
       SELECT "LocationArea"
            , row_number() OVER (PARTITION BY "LocationArea") AS rn
       FROM   table1
       ) t1 ON t1."LocationArea" = t2."Location"
           AND t1.rn = t2.rn;
    

    Works for Postgres or SQL Server. MySQL doesn't support window functions, you would need a substitute:

    • SQL SELECT last entry without limiting

    To be clear: LEFT JOIN is just shorthand for LEFT OUTER JOIN, so you are already using an outer join. Your statement is a misunderstanding:

    I am using ZOHO reports which does not support outer join's.

    0 讨论(0)
  • 2020-12-12 08:35
    SELECT * FROM table1 LEFT JOIN table2 ON `table_1_primary_key` = `table_2_primary_key`
    

    Or SELECT colname FROM table1 LEFT JOIN table2 ON table_1.colname = table_2.colname

    Depending on the structure of your database

    0 讨论(0)
提交回复
热议问题