我有以下表格布局
ACCIDENTS包含事故ID
ACCIDENT_TO_CAR包含事故和车牌之间的关系
REPORT包含车牌和驱动程序名称
使用以下联接:
SELECT T_ACCIDENTS.ACCIDENT_ID,DRIVER_NAME
from T_ACCIDENTS
inner join T_ACCIDENT_TO_CAR on T_ACCIDENT_TO_CAR.ACCIDENT_ID = T_ACCIDENTS.ACCIDENT_ID
inner join T_REPORT on T_ACCIDENT_TO_CAR.PLATE = T_REPORT.PLATE
and DRIVER_NAME in ('Foo','Moo')
目前司机'Foo'在报告中出现两次,因为他的两辆车出了车祸。
如何通过获取单个记录ACCIDENT_TO_CAR来限制加入驱动程序的结果 所以换言之,基于驱动程序的报告是不同的
测试数据:
CREATE TABLE "T_ACCIDENTS" ("ACCIDENT_ID" VARCHAR2(20))
Insert into T_ACCIDENTS (ACCIDENT_ID) values ('1');
Insert into T_ACCIDENTS (ACCIDENT_ID) values ('2');
Insert into T_ACCIDENTS (ACCIDENT_ID) values ('3');
CREATE TABLE "T_ACCIDENT_TO_CAR"
(
"PLATE" VARCHAR2(20 BYTE),
"ACCIDENT_ID" VARCHAR2(20 BYTE)
)
Insert into T_ACCIDENT_TO_CAR (PLATE,ACCIDENT_ID) values ('1','1');
Insert into T_ACCIDENT_TO_CAR (PLATE,ACCIDENT_ID) values ('2','1');
Insert into T_ACCIDENT_TO_CAR (PLATE,ACCIDENT_ID) values ('4','2');
Insert into T_ACCIDENT_TO_CAR (PLATE,ACCIDENT_ID) values ('3','1');
Insert into T_ACCIDENT_TO_CAR (PLATE,ACCIDENT_ID) values ('2','2');
CREATE TABLE "T_REPORT"
(
"PLATE" VARCHAR2(20 BYTE),
"DRIVER_NAME" VARCHAR2(20 BYTE)
)
Insert into T_REPORT (PLATE,DRIVER_NAME) values ('1','Foo');
Insert into T_REPORT (PLATE,DRIVER_NAME) values ('2','Foo');
Insert into T_REPORT (PLATE,DRIVER_NAME) values ('3','Moo');
Insert into T_REPORT (PLATE,DRIVER_NAME) values ('4','Bar');
UPDATE 对不起,数据集和查询不正确,我修好了!
答案 0 :(得分:2)
使用DISTINCT
关键字告诉Oracle仅包含唯一记录。
SELECT DISTINCT T_ACCIDENTS.ACCIDENT_ID,T_REPORT.DRIVER_NAME
from T_ACCIDENTS
inner join T_ACCIDENT_TO_CAR on T_ACCIDENT_TO_CAR.ACCIDENT_ID = T_ACCIDENTS.ACCIDENT_ID
inner join T_REPORT on T_ACCIDENT_TO_CAR.PLATE = T_REPORT.PLATE;
GROUP BY ACCIDENT_ID
并按字母顺序选择名字的驱动程序。
SELECT T_ACCIDENTS.ACCIDENT_ID, MIN(DRIVER_NAME) DRIVER_NAME
from T_ACCIDENTS
inner join T_ACCIDENT_TO_CAR on T_ACCIDENT_TO_CAR.ACCIDENT_ID = T_ACCIDENTS.ACCIDENT_ID
inner join T_REPORT on T_ACCIDENT_TO_CAR.PLATE = T_REPORT.PLATE
and DRIVER_NAME in ('Foo','Moo')
GROUP BY T_ACCIDENTS.ACCIDENT_ID;