我有三张桌子:
SN | Table Name | Primary Key | Foreign Key | Attribute
-----------------------------------------------------------------
1 | salesArea | salesAreaID | | areaDescription
2 | store | storeID | salesAreaID |
3 | salesPerson | salesPersonID | storeID | salesPersonName
我正在努力获取salesPersonName
与某个salesArea
相同的salesPerson
个人。{/ p>
例如,名为David的salesPerson
在storeID
23中工作,该salesArea
23位于NE salesPerson
中。
另有storeID
个名为Bob的salesArea
34工作,也在NE SELECT salesPersonName,
salesPersonID,
st.salesAreaID,
areaDescription,
sp.storeId
FROM salesperson as sp, salesArea as sa, store as st
。
到目前为止,我的查询是......
storeID
我很困惑如何让它获得“大卫”的salesArea
,然后检索salesArea
是什么。然后使用salesPersons
,使用salesArea
检索所有storeID
。
Salesperson表仅提供store
,但salesArea
为storeID
提供了group by
。
指向正确的方向会很好,加入条款?有些人喜欢{{1}}?
答案 0 :(得分:0)
我假设:
因此,我们首先要查找传递的销售人员的区域ID:
SELECT sp.SalesPersonID, st.SalesAreaID
FROM salesperson as sp
INNER JOIN store as st on sp.StoreID = st.StoreID
WHERE sp.SalesPersonName = 'David'
现在,我们可以使用此查询的结果然后执行问题的第二部分,即“获取给定salesarea中的其他人”。例如,如果上面的查询返回SalesAreaID = 23和SalesPersonID = 10,我们的第二个查询将如下所示:
SELECT sp.SalesPersonID, sp.SalesPersonName, st.StoreID
FROM stores st
INNER JOIN salespersons sp on st.StoreID = sp.StoreID
WHERE st.SalesAreaID = 23 and sp.SalesPersonID <> 10
但是,我们可以将两个查询组合成一个执行相同操作的查询:
SELECT sp2.SalesPersonID, sp2.SalesPersonName, st2.StoreID
FROM salesperson as sp
-- Join to stores to get the areaID of the salesperson passed (multiplicity 1)
INNER JOIN store as st on sp.StoreID = st.StoreID
-- self join to store to get all stores in that area (multiplicity 1 x Stores[area])
INNER JOIN store as st2 on st.SalesAreaID = st2.SalesAreaID
-- get all salespersons assigned to all stores in the area (multiplicity 1 x salespersons[area])
INNER JOIN salesperson as sp2
on st2.StoreID = sp2.StoreID
-- only return "other" salespersons
and sp2.SalesPersonID <> sp.SalesPersonID
WHERE sp.SalesPersonName = 'David'
Etvoilà,我们有一个查询,将所有其他销售人员与通过的销售人员放在同一区域。