SELECT FirstName,
LastName
FROM AdventureWorks.Person.Contact a
INNER JOIN [AdventureWorks].[HumanResources].[Employee] b
ON a.ContactID = b.ContactID
WHERE b.EmployeeID IN (
SELECT SalesPersonID
FROM AdventureWorks.Sales.SalesPerson c
WHERE c.Bonus = 5000)
如何将上面的子查询更改为Correlated子查询?
答案 0 :(得分:0)
我认为这是你正在寻找的东西。只需将查询移到FROM
部分,然后使用JOIN
根据WHERE
子句中的相同条件过滤结果,除非您引用结果集(RS) )子查询返回。
SELECT FirstName,
LastName
FROM AdventureWorks.Person.Contact a
INNER JOIN [AdventureWorks].[HumanResources].[Employee] b
ON a.ContactID = b.ContactID
INNER JOIN (SELECT SalesPersonID
FROM AdventureWorks.Sales.SalesPerson c
WHERE c.Bonus = 5000) AS RS ON b.EmpoyeeID = RS.SalesPersonID
虽然这是有用的,但通过直接在SalesPerson表中使用JOIN
可以更轻松,更快捷地完成。
SELECT FirstName,
LastName
FROM AdventureWorks.Person.Contact a
INNER JOIN [AdventureWorks].[HumanResources].[Employee] b
ON a.ContactID = b.ContactID
INNER JOIN SalesPersonID c
ON b.EmpoyeeID = c.SalesPersonID
and c.bonus = 5000
答案 1 :(得分:0)
你为什么这样做?对于简单的JOIN
:
SELECT
FirstName,
LastName
FROM AdventureWorks.Person.Contact a
INNER JOIN [AdventureWorks].[HumanResources].[Employee] b
ON a.ContactID = b.ContactID
INNER JOIN AdventureWorks.Sales.SalesPerson c
ON b.EmployeeID = c.SalesPersonID and c.Bonus = 5000
如果必须为此使用相关子查询,我能想到的唯一方法是:
SELECT
FirstName,
LastName
FROM AdventureWorks.Person.Contact a
INNER JOIN [AdventureWorks].[HumanResources].[Employee] b
ON a.ContactID = b.ContactID
WHERE 5000 IN (
SELECT bonus
FROM AdventureWorks.Sales.SalesPerson c
WHERE c.SalesPersonID = b.employeeID)
在这种情况下,子查询必须在外部查询的每次迭代中执行,这有时很有用,但同样,我在这里没有看到这一点。
答案 2 :(得分:0)
检查评论以便更好地理解。
SELECT firstname,
lastname
FROM
adventureworks.person.contact a
INNER JOIN
[AdventureWorks].[HumanResources].[employee] b ON a.contactid = b.contactid
INNER JOIN adventureworks.sales.salesperson c ON b.employeeid = c.salespersonid
--if the below result not give satisfy answer, then comment below line and uncomment the comment line
AND c.bonus = 5000 --this will apply and might be give the dupliate entry.
--where c.bonus = 5000 --where cluase apply after all condiotion of inner join apply