2014-03-24 42 views
0

在SQL +中,我創建了2個表來存儲數據,1個表來交叉引用它們。目標是能夠編寫一個單獨的查詢,告訴我哪輛車在哪個經銷店,哪個經銷商提供哪輛車等。問題是,當我查詢任何東西時,每輛車都在每個經銷商中。如何正確地將2個SQL表與參考錶鏈接起來

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; 

午夜搬家公司(100)和布巴的進口(200)都應該只有1-6轎車和進口汽車(300)應該有車7-12只。相反,所有經銷商都擁有所有的汽車,我希望能找出一些幫助來找出原因。

回答

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

+0

,完美的工作,謝謝。 – Codarus

相關問題