我尝试使用“Exist”和“IN”。我不仅没有成功,它似乎也不是一个有效的解决方案。
这是一个简化的例子:
TblMyTable 的
UserName1 - 成绩 - 用户名2 - 成绩
我需要一个存在相互关系/存在的查询。
我的意思是,查询返回的结果仅包括同一行中的用户,其中UserName1和UserName2 相互(有关更好的示例,请参见下图) /解释)。
任何用户都可以与任何其他用户合作。
所以结果将是(顺序无关紧要)理想地在一行中:
约翰 - 5000 - 玛丽 - 3000
要么
玛丽 - 3000 - 约翰 - 5000
一句话是,它是一个动态变化的表,活跃的用户使用F.Key到主用户的表,它有P.Key。
请参阅下面的图片以获得更好的示例/解释。
数据库是SQL 2005。
很多人提前
*编辑:希望有助于解释所有内容的截图。
最终结果应该是2行,因为只有它们在TblDynamicUserList中具有相互关系:
ana - 电话 - 3000 --- RanAbraGmail - Wifi - 2000
和
anaHeb - 电话 - 5000 --- RoyP - 电话 - 4000
http://www.marketing2go.co.il/SqlQuestion.jpg
答案 0 :(得分:2)
这样的事情对你有用:
With ManagerWorkers As
(
-- get managers with workers
Select Managers.WorkerUsername As ManagerUsername, Workers.WorkerUsername
From tblMyTable As Managers
Join tblMyTable As Workers
On Workers.ManagerUsername = Managers.WorkerUsername
)
Select *
From ManagerWorkers
Union All
-- get workers that have a manager in the above list
Select WorkerUsername, ManagerUsername
From tblMyTable
Where Exists( Select 1
From ManagerWorkers
Where ManagerWorkers.ManagerUsername = tblMyTable.ManagerUsername
)
编辑:鉴于对问题的更新如何进行以下查询:
Select D1.u_username, U1.Permission, U1.Grade, D1.f_username, U2.Permission, U2.Grade
from tblDynamicUserList As D1
Join tblDynamicUserList As D2
On D2.u_username = D1.f_username
And D2.f_username = D1.u_username
Join tblUsers As U1
On U1.u_username = D1.u_username
Join tblUsers As U2
On U2.u_username = D2.u_username
答案 1 :(得分:1)
这有点涉及查询,但按要求工作。它基本上将两个表连接两次,然后比较两侧匹配的位置。比较子句确保最终where子句中的“NOT”不返回重复项。
SELECT F.UserU, F.UserV
FROM
(SELECT U.u_userName AS UserU, V.u_username AS UserV
FROM TblUsers U INNER JOIN TblDynamicUserList D
ON U.u_username = D.U_username
INNER JOIN TblUsers V On V.u_username = D.F_UserName) F,
(SELECT U.u_userName AS UserU, V.u_username AS UserV
FROM TblUsers U INNER JOIN TblDynamicUserList D
ON U.u_username = D.U_username
INNER JOIN TblUsers V On V.u_username = D.F_UserName) G
WHERE (F.UserU = G.UserV AND F.UserV = G.UserU AND F.UserU < F.UserV)
AND NOT (F.UserU = G.UserV AND F.UserV = G.UserU AND F.UserU > F.UserV)