[FIXED] Oracle SQL Query with joining four tables to get only one row of multiple entries

Issue

My tables are set up something like this:

Table 1            Table 2                            Table 3        
+-------+-----+    +-------+-------+-------+-----+    +-------+-----+
| ID    | ... |    | ID    | T1_ID | T3_ID | ... |    | ID    | ... |
+-------+-----+    +-------+-------|-------|-----|    |-------|-----|
|  101  | ... |    |  202  |  101  |  301  | ... |    |  300  | ... |
|  102  | ... |    |  203  |  101  |  302  | ... |    |  302  | ... |
|  104  | ... |    |  204  |  101  |  302  | ... |    |  314  | ... |
+-------+-----+    |  205  |  101  |  302  | ... |    +-------+-----+
                   |  206  |  104  |  327  | ... |                   
                   +-------+-------+-------+-----+                   

I want to construct a subquery statement that will select only one row of table 2 for an given id of table 1, if table2.t3_id exists in table 3.

The important point is that there maybe exist multiple rows with same t3_id in table 2. So, the foreign key relation between table 2 and table 3 is not unique or does not exist at all.

My idea was the following statement:

inner join 
(
    SELECT * 
    FROM (
        SELECT t3_id, t1_id, id 
        FROM table2 
        WHERE EXISTS 
        (
            SELECT id 
            FROM table3
        )
    ) 
    WHERE ROWNUM=1
) tb2 ON tb1.id = tb2.t1_id

This statement returns multiple rows, but I only need one. How do I do this?


Solution

Not tested but should do what you need

SELECT *
FROM table1 t1 JOIN table2 t2 
ON ( t1.id = t2.t1_id
     AND EXISTS ( SELECT 'x'
                  FROM table3 t3
                  WHERE t2.t3_id = t3.id
                 )
     AND NOT EXISTS ( SELECT 'a'
                      FROM table2 t22 
                      WHERE t22.t1_id = t2.t1_id
                      AND t22.id < t2.id
                     )
   )


Answered By - Javaluca
Answer Checked By - David Marino (sql.easybugfix Volunteer)

Related Posts

Post a Comment