使用EXISTS的SQL查询无法正常工作

时间:2017-09-11 16:09:29

标签: mysql sql

这两个SQL查询返回相同的结果

SELECT DISTINCT ItemID
FROM Sale INNER JOIN Department
ON Department.DepartmentID = Sale.DepartmentID
WHERE DepartmentFloor = 2
ORDER BY ItemID


SELECT DISTINCT ItemID
FROM Sale
WHERE EXISTS
(SELECT *
FROM Department
WHERE Sale.DepartmentID = Department.DepartmentID
AND DepartmentFloor = 2)
ORDER BY ItemID;

Exists中的子查询返回True所以为什么secod查询不会返回等效的

SELECT DISTINCT ItemID
FROM Sale

与上述两种结果不同。

3 个答案:

答案 0 :(得分:1)

你对EXISTS()感到困惑。它基于表格相关而逐行发生,而不仅仅是一个真/假。子查询的这一行是您的相关子句:

Sale.DepartmentID = Department.DepartmentID

它说“只显示Sale.ItemIDs,其中ItemID的Sale.DepartmentID在Department中。”

它实现了与连接谓词相同的功能,就像在第一个查询中一样:

FROM Sale S
JOIN Department D on S.DepartmentID = D.DepartmentID --here

相反,这个查询:

SELECT DISTINCT ItemID
FROM Sale

没有限制因素。

另外,您还可以使用以下方法进一步限制每个查询的结果:

WHERE DepartmentFloor = 2

但我不认为这是让你失望的部分,我认为这是每个记录都会出现相关子查询的概念。如果你要删除你的correlating子句,那么子查询实际上总会返回true,你会得到所有结果。

答案 1 :(得分:1)

子查询并不总是返回true。它将评估每一行,加入DepartmentFloor为2的DepartmentID。

SQL Fiddle

MySQL 5.6架构设置

CREATE TABLE Sale ( ItemID int, DepartmentID int ) ;

INSERT INTO Sale ( ItemID, DepartmentID )
VALUES (1,1), (2,2), (3,3), (4,1), (5,4), (6,2), (7,3), (8,4) ;

CREATE TABLE Department ( DepartmentID int, DepartmentFloor int ) ;

INSERT INTO Department ( DepartmentID, DepartmentFloor )
VALUES (1,1), (2,1), (3,2), (4,2) ;

查询1

SELECT *
FROM Department
WHERE DepartmentFloor = 2 

Results :这仅列出了部门2上的部门。

| DepartmentID | DepartmentFloor |
|--------------|-----------------|
|            3 |               2 |
|            4 |               2 |

查询2

SELECT *
FROM Sale

Results :这会列出您的所有销售。

| ItemID | DepartmentID |
|--------|--------------|
|      1 |            1 |
|      2 |            2 |
|      3 |            3 |
|      4 |            1 |
|      5 |            4 |
|      6 |            2 |
|      7 |            3 |
|      8 |            4 |

查询3

SELECT *
FROM Sale
WHERE DepartmentID IN (3,4)

Results :这个显示了您的EXISTS语句的等价物。它只显示我的数据中将匹配的4行。因此,您只能获得ItemID 3,5,7和8。

| ItemID | DepartmentID |
|--------|--------------|
|      3 |            3 |
|      5 |            4 |
|      7 |            3 |
|      8 |            4 |

答案 2 :(得分:0)

因为查询的uppper部分等同于

   SELECT DISTINCT ItemID FROM Sale where EXISTS (true)

鞋面是真正检查条件的唯一查询..