Erik Åstrand
Erik Åstrand

Reputation: 379

SQL Simple SELECT Query

create table Person(

SSN INT,
Name VARCHAR(20),
primary key(SSN)

);

create table Car(

PlateNr INT,
Model VARCHAR(20),
primary key(PlateNr)

);

create table CarOwner(

SSN INT,
PlateNr INT,
primary key(SSN, PlateNR)
foreign key(SSN) references Person (SSN),
foreign key(PlateNr) references Car (PlateNr)

);

Insert into Person(SSN, Name) VALUES ('123456789','Max');
Insert into Person(SSN, Name) VALUES ('123456787','John');
Insert into Person(SSN, Name) VALUES ('123456788','Tom');


Insert into Car(PlateNr, Model) VALUES ('123ABC','Volvo');
Insert into Car(PlateNr, Model) VALUES ('321CBA','Toyota');
Insert into Car(PlateNr, Model) VALUES ('333AAA','Honda');

Insert into CarOwner(SSN, PlateNr) VALUES ('123456789','123ABC');
Insert into CarOwner(SSN, PlateNr) VALUES ('123456787','333AAA');

The problem I'm having is the SELECTE query I wanna make. I wan't to be able to SELECT everything from the Person and wan't the include the PlateNr of the car he's the owner of, an example:

PERSON

---------------------------------
 SSN            NAME     Car

123456789       Max      123ABC
123456787       John     3338AAA
123456788       Tom      

----------------------------------

So, I want to be able to show everything from the Person table and display the content of CarOwner aswell if the person is in fact a CarOwner. What I have so far is: "SELECT * from Person, CarOwner WHERE Person.SSN = CarOwner.SSN;". But this obviously results in only showing the person(s) that are CarOwners.

Hope I explained me well enough, Thanks.

Upvotes: 2

Views: 136

Answers (2)

Dev
Dev

Reputation: 3580

select ssn, name, car

from Person p

LEFT OUTER JOIN CarOwner co

ON p.SSN = co.SSN

LEFT OUTER JOIN Car c

ON co.PlateNr = c.PlateNr

Upvotes: 1

Joe Taras
Joe Taras

Reputation: 15379

Try this:

SELECT p.*, c.*
FROM Person p
LEFT OUTER JOIN CarOwner co
ON p.SSN = co.SSN
LEFT OUTER JOIN Car c
ON co.PlateNr = c.PlateNr

Show SQLFiddle

P.S. I've changed the type of your primary key PlateNr (in varchar and not in int)

Upvotes: 2

Related Questions