Oracle SQL:WHERE NOT EXISTS 无法正常运行
Posted
技术标签:
【中文标题】Oracle SQL:WHERE NOT EXISTS 无法正常运行【英文标题】:Oracle SQL: WHERE NOT EXITSTS not functioning properly 【发布时间】:2016-12-09 05:59:43 【问题描述】:第一张桌子
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');
第二张桌子:
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');
以下带有减号运算符的查询显示了正确的结果:
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';
以下 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');
【问题讨论】:
【参考方案1】:以下工作。 第二个 WHERE 子句必须具有一个别名,该别名引用第一个 FROM 子句中列出的表,该表拥有第一个 SELECT 子句中列出的所有列。
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');
更好的查询:
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');
感谢“Joel Murach mysql”教科书提出类似问题。
【讨论】:
以上是关于Oracle SQL:WHERE NOT EXISTS 无法正常运行的主要内容,如果未能解决你的问题,请参考以下文章
oracle SQL查询中,如何在where中用条件语句,判断不同情况,追加不同的And条件?
基于过程输入变量的条件 Where 子句 Oracle SQL
oracle 形式:pl/sql 中 where 子句中的 max 子句