SQL查询从两列中选择相关数据

时间:2011-12-03 08:31:32

标签: sql-server-2008

我有一个像这样填充的SQL表'名称'

 slno          from        to  
  1              a          e 
  2              a          b
  3              c          d
  4              c          e 
  .......  like this 

这些全部记录在用户需要显示他们相关的人员 现在我需要一个select语句来选择相关的。

firstly  i used 

   Select * from names where from= @zx        
   (@zx is the session )

通过这个我可以得到只有a和c的值。

但是我需要显示b,d和e的相关数据,我只需要使用一个select命令。是否有任何选择命令来选择相互关联的数据。每次登录的人都需要显示他们的相关信息。

2 个答案:

答案 0 :(得分:0)

您需要使用内部联接来引用表两次。

select * 
from 
  names as t1 inner join 
  names as t2 on t1.[from] = t2.[to] 
where t1.[from]= @zx

如果您尝试以递归方式执行此操作,则无法在单个select命令中对其进行管理。您可以将逻辑放入一个存储过程,该过程将多次遍历数据集,直到您的集合被构建,然后返回完整集。

答案 1 :(得分:0)

目前还不清楚你想要什么。是否要显示会话的用户,以及第一组用户通过“从 - 到”关系(让我们称之为父母/子女)的用户?

或者您是否也希望显示SECOND用户列表与之相关的内容?

E.g。对于这些数据:

slno   from     to
 1      a         b
 1      b         c
 1      c         d

您想要显示:

  • a和b

  • a-b,b-c和c-d对?

对于a-b,请执行:

 Select * from names where from= @zx        

 UNION

 -- For a large set of data, use inner join instead
 select * from names 
 where from IN
    (Select to from names where from= @zx)      
  and from= @zx        

如上所述,第二个应该真正作为一个连接来完成:

 Select * from names where from= @zx        

 UNION

 Select n2.* from names as n_from, names as n2
 where n1.from= @zx and n2.from=n1.to

对于另一个选项,你想要的基本上是一个使用一些树遍历算法的递归检索。

就关系数据而言,你不能在 SQL中做到这一点。您必须使用循环(在SQL或驱动程序软件中),或者,如果您的数据库允许,您可以编写实际上相同的递归表达式。

幸运的是,SQL Server实际上允许后者。如以下优秀博客文章所示:http://blog.sqlauthority.com/2008/07/28/sql-server-simple-example-of-recursive-cte/  (将EmployeeID替换为from,将ManagerID替换为from)

USE AdventureWorks
GO
WITH Emp_CTE AS (
SELECT EmployeeID, ContactID, LoginID, ManagerID, Title, BirthDate
FROM HumanResources.Employee
WHERE ManagerID IS NULL
UNION ALL
SELECT e.EmployeeID, e.ContactID, e.LoginID, e.ManagerID, e.Title, e.BirthDate
FROM HumanResources.Employee e
INNER JOIN Emp_CTE ecte ON ecte.EmployeeID = e.ManagerID
)
SELECT *
FROM Emp_CTE
GO
相关问题