1

I want to know the way join works,I have 3 tables users, addresses and location, users and addresses tables has data but not in location. When i made a join with addresses from users it return data but when i joined with location it don't return data, my question is why it is nil, because i joined user to address and user to location, so if user has data in address table then it will return that data but not in location so do not return location data in location columns. My schema is

 create temporary table users (
   id serial,
   username VARCHAR(25) NOT NULL,
   PRIMARY KEY (id)
 );

 CREATE temporary TABLE addresses (
   id serial,
   user_id int NOT NULL,
   city VARCHAR(30) NOT NULL,
   PRIMARY KEY (id),
   CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES users (id)
 );

 CREATE temporary TABLE location (
   id serial,
   user_id int NOT NULL,
   state VARCHAR(30) NOT NULL,
   PRIMARY KEY (id),
   CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES users (id)
 );

 insert into users(username) values ('u1'), ('u2'), ('u3'), ('u4')
 insert into addresses(user_id, city) values (1, 'c1'), (2,'c2'), (3,'c3')


 select * 
 from users u 
    inner join addresses a on u.id=a.user_id 
    inner join location l on u.id=l.user_id;

 insert into location(user_id, state) values (3, 's2')
HarsHarI
  • 901
  • 4
  • 11
  • 5
    Because you're using all inner joins. If one of the tables is "optional" (may or may not have matching rows) you need to use an outer join. – Andrew Sep 12 '18 at 18:20
  • 3
    I think you are looking for a left join. You should definitly read [this](https://stackoverflow.com/questions/17946221/sql-join-and-different-types-of-joins) – randomDude1001 Sep 12 '18 at 18:20
  • 3
    Or read [this](https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins), very helpful. – Andrew Sep 12 '18 at 18:22
  • @Andrew Thanks very much it's really a help lot. Very nice tutorials. – HarsHarI Sep 12 '18 at 19:29

1 Answers1

0

An inner join requires matches in both tables. Outer joins allow you to handle situations where that is not true. Your query only shows inner joins.

Neville Kuyt
  • 29,247
  • 1
  • 37
  • 52