Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner join only if a field is not empty

Tags:

join

mysql

I could have done what I want with two request, but I want to make it with only one.

In fact, I have 4 tables with :

Table 1 : id, sub-id
Table 2 : id, sub-id
Table 3 : id, login
Table 4 : id, login

I make a request like that :

SELECT Table1.id, Table1.sub-id, Table2.id, Table2.sub-id, 
   Table3.login, Table4.login FROM Table1
   INNER JOIN Table2 ON (Table1.id = Table2.id AND Table1.sub-id = Table2.sub-id)
   INNER JOIN Table3 ON (Table3.id = Table1.id)
   INNER JOIN Table4 ON (Table4.id = Table1.id)
   WHERE Table1.id = "my_id" AND Table1.sub-id = "my_subid"

I want to join Table3 only if id is not empty, if it is empty, I join Table4.

Do you have any ideas please ?

I've heard that a left join could help, but I'm not that accustomed to these keywords so ...?

like image 624
Sumz Avatar asked May 12 '11 14:05

Sumz


People also ask

Does inner join ignore NULL?

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.

Does inner join include NULL values?

When using left join, right join, full (outer) join, it is possible to return NULL value, while (inner) join, cross join will not return NUll value.

IS NOT NULL SQL join?

Yes, it will! Because a RIGHT JOIN will show all results that match (the first INNER JOIN we did) plus all rows from the RIGHT table that don't match (which in our case is one, the (NULL, 'Pan') row. You can fake a FULL JOIN in MySQL by taking the union between a LEFT JOIN and a RIGHT JOIN where the id is NULL .

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.


1 Answers

Like said in the other answers, you can use a left join. You can also add case statement to have only one login column :

SELECT 
    Table1.id, 
    Table1.sub-id, 
    Table2.id, 
    Table2.sub-id, 
    CASE 
        WHEN Table3.id IS NOT NULL THEN Table3.login
        ELSE Table4.login
    END CASE AS login
FROM Table1
INNER JOIN Table2 ON (Table1.id = Table2.id AND Table1.sub-id = Table2.sub-id)
LEFT JOIN Table3 ON (Table3.id = Table1.id)
LEFT JOIN Table4 ON (Table4.id = Table1.id)
WHERE Table1.id = "my_id" AND Table1.sub-id = "my_subid"
like image 134
krtek Avatar answered Oct 24 '22 21:10

krtek