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 ...?
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.
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.
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 .
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With