0

我有三张桌子:

SN | Table Name  | Primary Key   | Foreign Key | Attribute 
-----------------------------------------------------------------
1  | salesArea   | salesAreaID   |             | areaDescription
2  | store       | storeID       | salesAreaID | 
3  | salesPerson | salesPersonID | storeID     | salesPersonName 

我正在尝试获取与某个salesPersonName相同的任何人的(s)。salesAreasalesPerson

例如,一个salesPerson名叫 DavidstoreID在 NE 的 23工作salesArea。还有一个salesPerson叫 Bob 在storeID34 工作,也在 NE salesArea

到目前为止,我的查询是...

SELECT salesPersonName,
salesPersonID,
    st.salesAreaID,
    areaDescription,
    sp.storeId
  FROM salesperson as sp, salesArea as sa, store as st

我很困惑如何让它得到storeID'大卫'然后检索它是什么salesArea。然后用那个,用那个salesArea检索所有。salesPersonssalesArea

Salesperson 表只给出s ,storeID然后store给出s。salesAreastoreID

指向正确的方向会很好,加入子句?一些花哨的地方有一个group by

4

1 回答 1

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'

现在,我们可以使用此查询的结果来执行问题的第二部分,即“获取给定销售区域中的其他人”。例如,如果上述查询返回 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'

等等,我们有一个查询,提供与通过的销售人员在同一区域的所有其他销售人员。

于 2012-11-25T01:26:50.400 回答