我有3个表Vehicletype,VehicleOwner,VehicleInformation 其中VtypeID是Vehicletype中的PK和VehicleOwner和VehicleInformation中的FK。 Vehicletype有3条记录,VehicleOwner有7条记录,VehicleInformation也有7条记录。 当我加入Vehicletype和VehicleOwner时,我得到了7条记录accurate result in the result of 2 table joining
的准确结果但是当我用第三个表(VehicleInformation)加入这两个表时,我得到重复的行duplicate rows in the result of 3 tables joinningg 请指导我解决这个问题
答案 0 :(得分:1)
使用3表Vehicletype,VehicleOwner,VehicleInformation创建样本数据,其中typeID为PK。
/ *创建一个表* /
CREATE TABLE Vehicletype(Id integer PRIMARY KEY, Name text);
CREATE TABLE VehicleOwner(OwnerId integer, InfoID integer, TypeId integer, Name text);
CREATE TABLE VehicleInformation(InfoId integer, OwnerId integer, TypeId integer, INfo text);
/ *在Vehicletype表中创建几条记录* /
INSERT INTO Vehicletype VALUES(1,'TYPE1');
INSERT INTO Vehicletype VALUES(2,'TYPE2');
INSERT INTO Vehicletype VALUES(3,'TYPE3');
/ *在VehicleOwner表中创建几条记录* /
INSERT INTO VehicleOwner VALUES(1,1,1,'NAME1');
INSERT INTO VehicleOwner VALUES(2,2,2,'NAME2');
INSERT INTO VehicleOwner VALUES(3,3,3,'NAME3');
INSERT INTO VehicleOwner VALUES(4,4,1,'NAME4');
INSERT INTO VehicleOwner VALUES(5,5,2,'NAME5');
INSERT INTO VehicleOwner VALUES(6,6,3,'NAME6');
INSERT INTO VehicleOwner VALUES(7,7,1,'NAME7');
/ *在VehicleInformation表* /
中创建几条记录INSERT INTO VehicleInformation VALUES(1,1,1,'INFO1');
INSERT INTO VehicleInformation VALUES(2,2,2,'INFO2');
INSERT INTO VehicleInformation VALUES(3,3,3,'INFO3');
INSERT INTO VehicleInformation VALUES(4,4,1,'INFO4');
INSERT INTO VehicleInformation VALUES(5,5,2,'INFO5');
INSERT INTO VehicleInformation VALUES(6,6,3,'INFO6');
INSERT INTO VehicleInformation VALUES(7,7,1,'INFO7');
COMMIT;
/ *显示表* /
中的所有记录SELECT * FROM Vehicletype;
SELECT * FROM VehicleOwner;
SELECT * FROM VehicleInformation;
此联接将为您提供数据的唯一结果。
select *
from Vehicletype vt,VehicleOwner vo, VehicleInformation vi
where 1=1
and vt.id=vo.typeid
and vt.id=vi.typeid
and vo.ownerid=vi.ownerid
and vo.infoid=vi.infoid
and vo.typeid=vi.typeid;
答案 1 :(得分:0)
让我们说车主O1和O2都有车型V1。现在,如果车辆信息表I1,I2和I3中有三个记录,车辆类型为V1,那么当您创建联接时,您将在输出中显示以下行:
V1, O1, I1
V1, O1, I2
V1, O1, I3
V1, O2, I1
V1, O2, I2
V1, O2, I3
如果在输出中包含所有PK列,您将会更清楚地看到进展情况。