Marek Kotowski wrote:
Thank you. Your code works fine. But in my RDB
I have to add additional filter for table4.
It has at least one field more, 'name' for example.
So I have to include in the SELECT table4.name = 'something';
Or - in other words - table4.id3 = 'an id for something';
Where to put it? In WHERE or - with an AND operator -
in ON clause and which one (both ways don't work)?
If you want to have ONLY those rows where table4.name = 'something',
then you need to add this at the end of the query (after the joins)
where table4.name = 'something'
# So if we add to my previous example:
alter table table4 add name varchar(255);
update table4 set name='something' where id3=31;
update table4 set name='else' where id3=37;
# We would get this with our previous query:
+------+------+------+------+------+------+-----------+
| id | id | id2 | id2 | id3 | id3 | name |
+------+------+------+------+------+------+-----------+
| 1 | 1 | 21 | 21 | 31 | 31 | something |
| 2 | 2 | 22 | 22 | 32 | NULL | NULL |
| 4 | NULL | NULL | NULL | NULL | NULL | NULL |
| 5 | 5 | 25 | NULL | NULL | NULL | NULL |
| 7 | 7 | 27 | 27 | 37 | 37 | else |
| 8 | NULL | NULL | NULL | NULL | NULL | NULL |
+------+------+------+------+------+------+-----------+
# And this would be our new query:
SELECT * FROM table1
LEFT JOIN table2 on (table1.id = table2.id)
LEFT JOIN table3 on (table2.id2 = table3.id2)
LEFT JOIN table4 on (table3.id3 = table4.id3)
WHERE table4.name='something';
# And this would be the result:
+------+------+------+------+------+------+-----------+
| id | id | id2 | id2 | id3 | id3 | name |
+------+------+------+------+------+------+-----------+
| 1 | 1 | 21 | 21 | 31 | 31 | something |
+------+------+------+------+------+------+-----------+
# I could also show you what would happen if you put that
# new condition into join-clause:
SELECT * FROM table1
LEFT JOIN table2 on (table1.id = table2.id)
LEFT JOIN table3 on (table2.id2 = table3.id2)
LEFT JOIN table4 on (table3.id3 = table4.id3
AND table4.name='something');
+------+------+------+------+------+------+-----------+
| id | id | id2 | id2 | id3 | id3 | name |
+------+------+------+------+------+------+-----------+
| 1 | 1 | 21 | 21 | 31 | 31 | something |
| 2 | 2 | 22 | 22 | 32 | NULL | NULL |
| 4 | NULL | NULL | NULL | NULL | NULL | NULL |
| 5 | 5 | 25 | NULL | NULL | NULL | NULL |
| 7 | 7 | 27 | 27 | 37 | NULL | NULL |
| 8 | NULL | NULL | NULL | NULL | NULL | NULL |
+------+------+------+------+------+------+-----------+
As you can see, we would get all rows for table1, but values for table4
would be null, unless the name='something'. We could use both, but AFAIK
that would be just stupid. And it would give us the same results as it
would with only using where-clause.