在SQL +中,我创建了2个表来存储数据,1个用于交叉引用它们。我们的目标是能够编写一个单一的查询,告诉我哪辆车在哪家经销店,哪家经销商提供哪辆车等等。问题在于,当我查询任何东西时,每辆车都在每个经销店。
drop table car_dealer;
drop table car;
drop table dealer;
create table dealer(
did NUMBER PRIMARY KEY,
dname VARCHAR2(20)
);
create table car(
cid NUMBER PRIMARY KEY,
cname VARCHAR2(20)
);
create table car_dealer(
cid NUMBER REFERENCES car(cid),
did NUMBER REFERENCES dealer(did),
CONSTRAINT pk_car_dealer PRIMARY KEY (cid,did)
);
INSERT INTO car
VALUES (1,'Buick Skylark');
INSERT INTO car
VALUES (2,'H2 Hummer');
INSERT INTO car
VALUES (3,'Chevy Suburban');
INSERT INTO car
VALUES (4,'BMW Z3');
INSERT INTO car
VALUES (5,'BMW 328i');
INSERT INTO car
VALUES (6,'Jeep Wrangler');
INSERT INTO car
VALUES (7,'Ford Focus');
INSERT INTO car
VALUES (8,'Range Rover');
INSERT INTO car
VALUES (9,'Toyota Supra');
INSERT INTO car
VALUES (10,'Ferrari Testarosa');
INSERT INTO car
VALUES (11,'Jaguar X12');
INSERT INTO car
VALUES (12,'Ford Fairmont');
INSERT INTO dealer
VALUES (100,'Midnight Movers');
INSERT INTO dealer
VALUES (200,'Bubbas Imports');
INSERT INTO dealer
VALUES (300,'Import Motors');
INSERT INTO car_dealer (cid,did)
VALUES (1,100);
INSERT INTO car_dealer (cid,did)
VALUES (2,100);
INSERT INTO car_dealer (cid,did)
VALUES (3,100);
INSERT INTO car_dealer (cid,did)
VALUES (4,100);
INSERT INTO car_dealer (cid,did)
VALUES (5,100);
INSERT INTO car_dealer (cid,did)
VALUES (6,100);
INSERT INTO car_dealer (cid,did)
VALUES (1,200);
INSERT INTO car_dealer (cid,did)
VALUES (2,200);
INSERT INTO car_dealer (cid,did)
VALUES (3,200);
INSERT INTO car_dealer (cid,did)
VALUES (4,200);
INSERT INTO car_dealer (cid,did)
VALUES (5,200);
INSERT INTO car_dealer (cid,did)
VALUES (6,200);
INSERT INTO car_dealer (cid,did)
VALUES (7,300);
INSERT INTO car_dealer (cid,did)
VALUES (8,300);
INSERT INTO car_dealer (cid,did)
VALUES (9,300);
INSERT INTO car_dealer (cid,did)
VALUES (10,300);
INSERT INTO car_dealer (cid,did)
VALUES (11,300);
INSERT INTO car_dealer (cid,did)
VALUES (12,300);
select dname,
cname
from dealer,car
where did = 200;
select dname,
cname
from dealer,car
where cid = 4;
Midnight Movers(100)和Bubba's Imports(200)都应该只有1-6的车,而进口汽车(300)应该只有7-12的车。相反,所有经销商都拥有所有汽车,我想帮助找出原因。
答案 0 :(得分:3)
当您未指定连接时会发生这种情况。要获得正确的结果,您应该将查询更改为以下内容:
SELECT
d.dname, c.cname
FROM
car_dealer cd
JOIN
car c ON cd.cid = c.cid
JOIN
dealer d ON cd.did = d.did
WHERE
cd.did = 200;
SELECT
d.dname, c.cname
FROM
car_dealer cd
JOIN
car c ON cd.cid = c.cid
JOIN
dealer d ON cd.did = d.did
WHERE
cd.cid = 4;
此处SQL小提琴http://sqlfiddle.com/#!4/98833/4