let’s say I have 5 tables, as follows:
CREATE TABLE T1 (
FIRST_NAME VARCHAR2(100),
LAST_NAME VARCHAR2(100),
CITY NUMERIC,
SALARY NUMERIC);
CREATE TABLE T2 (
CITY NUMERIC,
DISTRICT NUMERIC);
CREATE TABLE T3 (
DISTRICT NUMERIC,
DOMAIN NUMERIC);
CREATE TABLE T4 (
DOMAIN NUMERIC,
DETAILS_BOOK NUMERIC);
CREATE TABLE T5 (
DETAILS_BOOK NUMERIC,
FIRST_NAME VARCHAR2(100),
LAST_NAME VARCHAR2(100),
EMAIL VARCHAR2(100));
INSERT INTO T1 VALUES ('john', 'doe',1001,1000);
INSERT INTO T1 VALUES ('jack', 'jill',1001,2000);
INSERT INTO T1 VALUES ('jeff', 'bush',1001,1500);
INSERT INTO T2 VALUES (1001,1);
INSERT INTO T3 VALUES (1,543);
INSERT INTO T4 VALUES (543,22);
INSERT INTO T5 VALUES (22,'john', 'doe','john@22.com');
INSERT INTO T5 VALUES (44,'john', 'doe','john@44.com');
INSERT INTO T5 VALUES (22,'jeff', 'bush','jeff@22.com');
INSERT INTO T5 VALUES (44,'jeff', 'bush','jeff@44.com');
now, I want all records from t1, with their salaries and emails, corresponding to tables t2, t3, and t4, such that the reuslt should be:
FIRST_NAME | LAST_NAME | SALARY | EMAIL
--------------------------------------------------
john | doe | 1000 | john@22.com
jeff | bush | 1500 | jeff@22.com
jack | jill | 2000 | (NULL)
what I got so far is:
SELECT T1.FIRST_NAME, T1.LAST_NAME,T1.SALARY,T5.EMAIL
FROM T1,T2,T3,T4,T5
WHERE T1.FIRST_NAME = T5.FIRST_NAME (+)
and T1.LAST_NAME = T5.LAST_NAME(+)
AND T1.CITY = T2.CITY
AND T2.DISTRICT = T3.DISTRICT
AND T3.DOMAIN = T4.DOMAIN
AND T4.DETAILS_BOOK = T5.DETAILS_BOOK
which returns only the first two rows.
Try this instead:
SQL Fiddle Demo
This will give you:
The problem is that the
INNER JOINafter theOUTER JOINmakes your joins works like anINNER, because, the inner joins eliminate those unmatched rows coming from the outer joins.Note that: I used the ANSI SQL-92 explicit
LEFT OUTER JOINsyntax, instead of the old implicitOUTERandINNERjoin syntax that you sued in your query.Please try to use the
LEFT OUTER JOINinstead of the old outer join syntax, and avoidINNER JOINafterOUTER JOINs.For more details, see these:
Bad habits to kick : using old-style JOINs..
Bad habits to kick : using table aliases like (a, b, c) or (t1, t2, t3)
Update:
When you have many tables references in the
FROMclause with theJOINbetween them, each table is joined with the next table begging from theFROMclause1, results a temporary result set, then this temporary result set is joined with the next table and so on. In case of theOUTER JOIN, there are left or right:LEFT JOINwill include those unmatched rows from the left table, where as,RIGHT JOINwill include those unmatched rows from the right table.Depending on the data you want to select, you have to watch out those tables in the two sides of the
JOINoperator and the order of them.1:This is just the logical query processing order, but in the actual order is always up to the query optimizer.