带有子句 "Exists" 的子查询,其中需要从两个表中收集信息
Subquery with a clause "Exists", where information need to be gathered from two tables
所以,有两个 table。一个列出了有关产品的所有信息(ID、ProductName、SupplierID、UnitPrice、Package、IsDiscontinued),另一个存储了有关供应商的信息(ID、CompanyName、ContactName、City、Country...)
我需要找到产品超过 100 美元的供应商。所以给出的代码如下:
SELECT CompanyName
FROM Supplier
WHERE EXISTS
( SELECT ProductName
FROM Product
WHERE supplierID = supplier.ID
AND unitprice > 100);
我不明白为什么在子查询中我们需要 SELECT ProductName 而不是 table Product 的任何其他字段?此外,当系统检测到所有单价 > 100 且 supplierID 与其他匹配的产品名称时 table,它从哪里收集公司名称?
实际上exists
只关心是否返回行而不是行中的值。因此,选择什么列没有区别。我通常只使用 1
:
WHERE EXISTS (SELECT 1
FROM Product
WHERE supplierID = supplier.ID AND unitprice > 100
)
1
很容易输入。
I don't understand why on subquery we need to SELECT ProductName not
any other field
您可以 select 任何其他列,甚至所有列,甚至像 select 1...
甚至 null
这样的常量:select null...
.
使用此子查询的目的是确保至少 EXISTS
行具有其 WHERE
子句中提供的属性。
when the system has detected all the product names with unitprice >
100 and matching supplierID with the other table, from where do it
gather what's the company's name?
语句是:
SELECT CompanyName
FROM Supplier
................
所以公司的名字当然是从tableSupplier
中收集当且仅当EXISTS
行在table Product
supplierID
等于来自 table Suppliers
的行的 ID
附加条件为 unitprice > 100
.
所以,有两个 table。一个列出了有关产品的所有信息(ID、ProductName、SupplierID、UnitPrice、Package、IsDiscontinued),另一个存储了有关供应商的信息(ID、CompanyName、ContactName、City、Country...) 我需要找到产品超过 100 美元的供应商。所以给出的代码如下:
SELECT CompanyName
FROM Supplier
WHERE EXISTS
( SELECT ProductName
FROM Product
WHERE supplierID = supplier.ID
AND unitprice > 100);
我不明白为什么在子查询中我们需要 SELECT ProductName 而不是 table Product 的任何其他字段?此外,当系统检测到所有单价 > 100 且 supplierID 与其他匹配的产品名称时 table,它从哪里收集公司名称?
实际上exists
只关心是否返回行而不是行中的值。因此,选择什么列没有区别。我通常只使用 1
:
WHERE EXISTS (SELECT 1
FROM Product
WHERE supplierID = supplier.ID AND unitprice > 100
)
1
很容易输入。
I don't understand why on subquery we need to SELECT ProductName not any other field
您可以 select 任何其他列,甚至所有列,甚至像 select 1...
甚至 null
这样的常量:select null...
.
使用此子查询的目的是确保至少 EXISTS
行具有其 WHERE
子句中提供的属性。
when the system has detected all the product names with unitprice > 100 and matching supplierID with the other table, from where do it gather what's the company's name?
语句是:
SELECT CompanyName
FROM Supplier
................
所以公司的名字当然是从tableSupplier
中收集当且仅当EXISTS
行在table Product
supplierID
等于来自 table Suppliers
的行的 ID
附加条件为 unitprice > 100
.