Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore SQL INNER JOIN if there are no records to join?

I have the following Join

INNER JOIN @SynonymTable AS A ON ([Products].[Title] LIKE A.[Synonym])

The @SynonymTable table variable contains (if needed) a list of items terms such as:

%shirt%
%blouse%
%petticoat%

These are all based on a list of a synonyms for a particular keyword search, such as the term 'shirt' - from this I can then find all items that may be related, etc. The problem is that if the there is no keyword supplied the query obviously does not join anything.

Is there anyway to eliminate the join or return all items if there are no items in the synonym table?

I've found posts such as Bypass last INNER JOIN in query but am unable to get it to work for my scenario?

Any help or advice would be great.

like image 831
Nathan Avatar asked Jan 03 '13 14:01

Nathan


People also ask

What happens if you use inner join with no conditions?

When using join or inner join , the on condition is optional. This is different from the ANSI standard and different from almost any other database. The effect is a cross join . Similarly, you can use an on clause with cross join , which also differs from standard SQL.

Does inner join ignore NULL values?

A join that displays only the rows that have a match in both joined tables. Columns containing NULL do not match any values when you are creating an inner join and are therefore excluded from the result set.

How do you exclude rows that don't join with another table?

Create a Query that joins table A and B with a LEFT JOIN in Cognos by selecting link type: table A. Key has "0 to N" values in table B, then added a Filter (these correspond to Where Clauses) for: table B. Key is NULL. Ran fast and like a charm.

How would you return data from 2 tables even if there are no matches?

The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.


1 Answers

You can use one select like this:

SELECT * FROM Products 
LEFT JOIN @SynonymTable AS A ON ([Products].[Title] LIKE A.[Synonym])
WHERE A.[Synonym] IS NOT NULL 
      OR NOT EXISTS (SELECT B.[Synonym] FROM @SynonymTable B)
like image 142
András Ottó Avatar answered Sep 17 '22 18:09

András Ottó