2016-12-09 15 views
0

第一テーブルが機能していないEXITSTS、NOT WHEREOracleのSQL:適切

CREATE TABLE qualified (
    facultyid integer NOT NULL, 
    courseid character varying(16) NOT NULL, 
    datequalified character varying(16), 
    dq2 date, 
    CONSTRAINT qualified_pkey PRIMARY KEY (facultyid, courseid) 
); 

INSERT INTO qualified VALUES (3467, 'ISM 4212', to_date('9/1995', 'MM/YYYY'), date '1995-09-01'); 
INSERT INTO qualified VALUES (4756, 'ISM 3112', to_date('9/1991', 'MM/YYYY'), date '1991-09-01'); 
INSERT INTO qualified VALUES (2143, 'ISM 3113', to_date('9/1988', 'MM/YYYY'), date '1988-09-01'); 
INSERT INTO qualified VALUES (4756, 'ISM 3113', to_date('9/1991', 'MM/YYYY'), date '1991-09-01'); 
INSERT INTO qualified VALUES (2143, 'ISM 3112', to_date('9/1988', 'MM/YYYY'), date '1988-09-01'); 
INSERT INTO qualified VALUES (3467, 'ISM 4930', to_date('9/1996', 'MM/YYYY'), date '1996-09-01'); 

第二表:

SELECT q.facultyid, facultyname 
FROM qualified q, faculty fa 
WHERE q.facultyid = fa.facultyid AND courseid = 'ISM 3113' 
MINUS 
SELECT q.facultyid, facultyname 
FROM qualified q, faculty fa 
WHERE q.facultyid = fa.facultyid AND courseid = 'ISM 4930'; 

CREATE TABLE faculty (
    facultyid integer NOT NULL, 
    facultyname character varying(25), 
    CONSTRAINT faculty_pkey PRIMARY KEY (facultyid) 
); 

INSERT INTO faculty VALUES (2143, 'Birkin'); 
INSERT INTO faculty VALUES (3467, 'Berndt'); 
INSERT INTO faculty VALUES (4756, 'Collins'); 

マイナス演算子では、次のクエリは正しい結果を表示次のWHERE NOT EXISTSは不正確な結果を表示します

SELECT q.facultyid, facultyname 
FROM qualified q, faculty fa 
WHERE q.facultyid = fa.facultyid AND courseid = 'ISM 3113' 
AND NOT EXISTS (SELECT q.facultyid, facultyname 
        FROM qualified q, faculty fa 
        WHERE q.facultyid = fa.facultyid AND courseid = 'ISM 4930'); 

答えて

0

次のように機能しました。 2番目のWHERE句には、最初のSELECT句にリストされるすべての列を持つ最初のFROM句にリストされている表を参照するALIASが必要です。

SELECT q.facultyid, facultyname 
FROM qualified q, faculty fa 
WHERE q.facultyid = fa.facultyid AND courseid = 'ISM 3113' 
AND NOT EXISTS (SELECT q.facultyid, facultyname 
        FROM qualified q2, faculty fa2 
        WHERE q2.facultyid = fa.facultyid AND courseid = 'ISM 4930'); 

より良いクエリ:同様の質問を持つための 'ジョエルMurach MySQLの' テキストブックへ

SELECT fa.facultyid, facultyname 
FROM qualified q, faculty fa 
WHERE q.facultyid = fa.facultyid AND courseid = 'ISM 3113' 
AND NOT EXISTS (SELECT facultyid 
        FROM qualified 
        WHERE facultyid = fa.facultyid AND courseid = 'ISM 4930'); 

感謝。