链接表 - 如何获取列表中的项目列表

时间:2015-10-04 04:43:43

标签: sql

我有一个名为AccountGroupLinks的链接表。它有两列:

  • AccountId
  • 的GroupId

对于分配给帐户X的每个组,获取分配给除Y组之外的每个组的不同帐户列表。我似乎无法想出这个SQL语句。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您需要自我加入才能执行此操作:

select distinct t2.GroupId, t2.AccountId
  from AccountGroupLinks t1
  join AccountGroupLinks t2
    on t2.GroupId = t1.GroupId
   and t2.GroupId <> 'Y'
 where t1.AccountId = 'X'

答案 1 :(得分:0)

谢谢@sstan。我试图做嵌套的select语句。这让我的方向正确。我不得不做一个小小的调整才能让它发挥作用:

select distinct t2.GroupId, t2.AccountId
  from AccountGroupLinks t1
  join AccountGroupLinks t2
    on t2.GroupId = t1.GroupId
   and t2.GroupId <> 'Y'
   and t2.accountId <> 'X'
 where t1.AccountId = 'X'