Oracle
 SQL >> Database >  >> RDS >> Oracle

Limitare un Join SQL alla Prima Riga Corrispondente

La parola operativa è FIRST. Puoi usare la funzione analitica FIRST_VALUE o la costruzione aggregata FIRST. Per FIRST o LAST, le prestazioni non sono mai peggiori e spesso migliori dell'equivalente FIRST_VALUE o LAST_VALUE, perché salti l'ordinamento extra della finestra e riduci così il costo di esecuzione:

select table_A.id, table_A.name, firstFromB.city from table_A join ( select table_B.id2, max(table_B.city) keep (dense_rank first order by table_B.city) city from table_b group by table_B.id2 ) firstFromB on firstFromB.id2 = table_A.id where 1=1 /* some conditions here */; 

Poiché la 12c ha introdotto l'operatore LATERAL insieme ai join CROSS/OUTER APPLY, ora puoi porre una subquery correlata sul lato destro di un JOIN:

select table_A.id, table_A.name, firstFromB.city from table_A cross apply ( select max(table_B.city) keep (dense_rank first order by table_B.city) city from table_b where table_B.id2 = table_A.id ) firstFromB where 1=1 /* some conditions here */;