How do I limit the number of rows returned by this LEFT JOIN to one?

前端 未结 6 475
孤城傲影
孤城傲影 2021-01-11 17:08

So I think I\'ve seen a solution to this however they are all very complicated queries. I\'m in oracle 11g for reference.

What I have is a simple one to many join w

6条回答
  •  执念已碎
    2021-01-11 17:53

    In Oracle, if you want 1 result, you can use the ROWNUM statement to get the first N values of a query e.g.:

    SELECT *
    FROM TABLEX
    WHERE
    ROWNUM = 1 --gets the first value of the result
    

    The problem with this single query is that Oracle never returns the data in the same order. So, you must oder your data before use rownum:

    SELECT *
    FROM
        (SELECT * FROM TABLEX ORDER BY COL1)
    WHERE
    ROWNUM = 1
    

    For your case, looks like you only need 1 result, so your query should look like:

    SELECT *
    FROM
        TABLE1 T1
        LEFT JOIN 
        (SELECT *
        FROM TABLE2 T2 WHERE T1.ASSIGNMENT = T2.ASSIGNMENT_GROUP
        AND
        ROWNUM = 1) T3 ON T1.ASSIGNMENT = T3.ASSIGNMENT_GROUP
    

提交回复
热议问题