sql = " SELECT * FROM userDetail ";
sql += " WHERE userId IN ";
sql += " (SELECT friendId FROM userFriends ";
sql += " WHERE approvalStatus='True' AND userId=" + userId;
sql += " UNION";
sql += " SELECT userId FROM userFriends ";
sql += " WHERE approvalStatus='True' AND friendId=" + userId + ")";
答案 0 :(得分:3)
在LINQ中,你可能会像:
var approvedUsers = db.UserFriends.Where(p => p.ApprovalStatus == "True");
var userIds = from p in approvedUsers
where p.UserId == userId || p.FriendId = userId
select p.UserId;
var friendsAndUser = db.UserDetails
.Where(detail => userIds.Contains(detail.UserId));
或者,使用联接:
var query = from user in db.UserFriends
where p.ApprovalStatus == "True"
where p.UserId == userId || p.FriendId == userId
join detail in db.UserDetails on user.UserId equals detail.UserId
select detail;
我怀疑这些都不会使用联盟。您可以使用LINQ的联合,如下所示:
var approvedUsers = db.UserFriends.Where(p => p.ApprovalStatus == "True");
var userIds = from p in approvedUsers
where p.UserId == userId
select p.UserId;
var friendIds = from p in approvedUsers
where p.FriendId = userId
select p.UserId;
var allIds = userIds.Union(friendIds);
var friendsAndUser = db.UserDetails
.Where(detail => userIds.Contains(detail.UserId));
......但是这很麻烦。我可能会加入。