我一直试图将这个SQL查询转换为Linq一段时间后现在没有成功。我发现在linq的连接中不能使用OR条件,所以我尝试了相同的SQL查询但是使用了子查询。子查询问题根本不起作用,它显示错误的数据。
带有JOIN的sqlquery:
SELECT DISTINCT Users.Fname FROM Friends
JOIN Users On Users.UserID = UserID2 OR Users.UserID = UserID1
WHERE UserID1 = 1 OR UserID2 = 1
AND Users.UserID != 1 AND Friends.PendingFriendRequest = 0
带子查询的sqlquery:
SELECT DISTINCT Users.Fname FROM Friends, Users
WHERE Users.UserID = Friends.UserID1 OR Users.UserID = Friends.UserID2
AND UserID1 = 1 OR UserID2 = 1
AND Users.UserID != 1 And Friends.PendingFriendRequest = 0
答案 0 :(得分:2)
在您的查询中,如果首先条件UserID1 = 1
匹配,则忽略查询的其余部分。
尝试在查询中添加括号:
SELECT DISTINCT Users.Fname FROM Friends
JOIN Users On Users.UserID = UserID2 OR Users.UserID = UserID1
WHERE (UserID1 = 1 OR UserID2 = 1)
AND Users.UserID != 1 AND Friends.PendingFriendRequest = 0
答案 1 :(得分:1)
是的,你是对的 - 在linq连接中不允许使用OR的多个连接条件,因为只支持equijoins和group连接。
要实现您的方案,一个解决方案是在linq中使用union。
例如:
var q = (from u in
(from u1 in users
join f1 in friends on u1.userId equals f1.user1Id
where !f1.PendingFriendRequest
select new {u1.Fname, FriendsWithId = f1.UserId, UserId = u2.UserId})
.Union(from u2 in users
join f2 in friends on u2.userId equals f2.user2Id
where !f2.PendingFriendRequest
select new {u2.Fname, FriendsWithId = f2.UserId, UserId = u2.UserId})
where u.FriendsWithId == 1
&& u.UserId != 1
select u.Fname
).Distinct();