SQL简单SELECT查询

时间:2013-09-26 12:25:16

标签: sql

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');

我遇到的问题是我想做的SELECTE查询。我不能从人物中选择所有东西,而不是包括他所拥有的汽车的PlateNr,例如:

PERSON

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

123456789       Max      123ABC
123456787       John     3338AAA
123456788       Tom      

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

所以,我希望能够显示Person表中的所有内容并显示CarOwner的内容,以及该人是否实际上是CarOwner。到目前为止我所拥有的是:“SELECT * from Person,CarOwner WHERE Person.SSN = CarOwner.SSN;”。但这显然导致只显示CarOwners的人。

希望我能很好地解释我,谢谢。

2 个答案:

答案 0 :(得分:2)

试试这个:

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

显示SQLFiddle

P.S。我已经更改了主键PlateNr的类型(在varchar而不是在int中)

答案 1 :(得分:1)

选择ssn,name,car

来自Person p

LEFT OUTER JOIN CarOwner co <​​/ p>

ON p.SSN = co.SSN

LEFT OUTER JOIN Car c

ON co.PlateNr = c.PlateNr