Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting a LEFT JOIN

Tags:

sql

oracle

I have a table, let's call it "a" that is used in a left join in a view that involves a lot of tables. However, I only want to return rows of "a" if they also join with another table "b". So the existing code looks like

SELECT ....
FROM main ...
...
LEFT JOIN a ON (main.col2 = a.col2)

but it's returning too many rows, specifically ones where a doesn't have a match in b. I tried

SELECT ...
FROM main ...
...
LEFT JOIN (
   SELECT a.col1, a.col2
   FROM a
   JOIN b ON (a.col3 = b.col3)) ON (a.col2 = main.col2)

which gives me the correct results but unfortunately "EXPLAIN PLAN" tells that doing it this way ends up forcing a full table scan of both a and b, which is making things quite slow. One of my co-workers suggested another LEFT JOIN on b, but that doesn't work because it gives me the b row when it's present, but doesn't stop returning the rows from a that don't have a match in b.

Is there any way to put the main.col2 condition in the sub-SELECT, which would get rid of the full table scans? Or some other way to do what I want?

like image 246
Paul Tomblin Avatar asked Apr 16 '09 20:04

Paul Tomblin


People also ask

Can you filter in a left join?

When doing a left join in SQL any filtering of the table after the join will turn it into an inner join. However there are some easy ways to do the filtering first. Suppose you've got some tables related to a website. The pages table describes the different pages on the site.

What is anti LEFT join?

One of the join kinds available in the Merge dialog box in Power Query is a left anti join, which brings in only rows from the left table that don't have any matching rows from the right table.

Is it better to filter on join or WHERE?

All three queries return the exact same result regardless of whether the filter and join condition are placed in the ON clause or the WHERE clause. As far as performance goes, it makes no difference whether the filter condition is placed in the ON clause or the WHERE in PostgreSQL.

IS LEFT join case sensitive?

In SQL Server, joins are case-insensitive. Case-sensitive collations are not supported with ArcGIS.


1 Answers

SELECT ...
FROM ....
LEFT JOIN ( a INNER JOIN b ON .... ) ON ....
like image 134
Joel Coehoorn Avatar answered Oct 03 '22 08:10

Joel Coehoorn