SQL Oracle IN运算符行为

时间:2018-06-08 08:09:29

标签: sql oracle

我使用Oracle而我无法解释这种行为:

SELECT DUMMY 
FROM   DUAL 
WHERE  DUMMY IN (SELECT DUMMY FROM z_sites);

返回

DUMMY
-----
X

而且:

SELECT DUMMY FROM z_sites;

返回

  

ORA-00904:" DUMMY" :识别非valide   00904. 00000 - "%s:无效的标识符"

所以在我的第一个查询中,子查询是错误的,但查询仍然可以自行解决?!

1 个答案:

答案 0 :(得分:6)

关于范围:

SELECT DUMMY 
FROM   DUAL 
WHERE  DUMMY IN (SELECT DUMMY FROM z_sites);

与:

相同
SELECT DUMMY 
FROM   DUAL 
WHERE  DUMMY IN (SELECT DUAL.DUMMY FROM z_sites);

鉴于:

SELECT DUMMY FROM z_sites;
-- there is no dummy column in z_sites table

为了让事情变得更有趣,你可以检查一下如果z_sites包含虚拟列会发生什么:

CREATE TABLE z_sites(dummy VARCHAR2(100));
INSERT INTO z_sites(dummy) VALUES('Y');

SELECT DUMMY 
FROM   DUAL 
WHERE  DUMMY IN (SELECT DUMMY FROM z_sites);
-- 0 rows selected
<=>
SELECT DUMMY 
FROM   DUAL 
WHERE  DUMMY IN (SELECT z_sites.DUMMY FROM z_sites);
-- 0 rows selected

SELECT DUMMY 
FROM   DUAL 
WHERE  DUMMY IN (SELECT DUAL.DUMMY FROM z_sites);

DUMMY
-----
X

<强> DBFiddle Demo

总结:始终在子查询中添加前缀以避免混淆。