我是Asp.net的新手
现在我想尝试启动一个社交网络项目

我有3张桌子

用户


  用户身份
  -用户名
    -电子邮件
     -密码
     -名称
     -用户照片


发布


  -Postid -Content -Postdate -Userid


好友列表


  朋友列表-用户ID-朋友-状态


我想加载我的朋友和我自己的帖子

这是我的SQL代码

select b.userid, a.Friendid, c.name, b.postid, b.Content, b.postdate, c.profilepic
from friendlist a
left join [user] c on a.friendid = c.userid
left join post b on a.friendid = b.userid
where a.userid = 1 AND a.Status = 1 OR a.Userid = 1
ORDER BY postid desc


我面临的问题是我的帖子会重复

例如,我的好友列表中有3个好友,我的每个帖子都会重复3次,而我的好友帖子保持正常。

这个SQL代码的任何解决方案?

最佳答案

如果表之间有关系并且正在使用Entity Framework。您可以简单地调用其“好友列表”下方的表。您可以使用此查询返回值来创建特定于该返回值的类

public class ListFriendsGroup
{
        public int UserId { get; set; }
        public int friendId  { get; set; }
        public int PostId{ get; set; }
        public string Name { get; set; }
        public string Content { get; set; }
        public DataTime PostData { get; set; }
        public string ProfilePic { get; set; }
}

var friendlist = Context.friendList.Include("user").Include("post")
// HERE .GroupBy(...
.Select(f => new ListFriendsGroup() { Userid = f.post.userid, FriendId = f.Friendid, Name = f.user.name, PostId = f.post.postid, Content = f.post.Content, PostData = f.post.postdate, Profilepic = f.user.profilepic }).ToList()


阅读有关Group By子句以执行数据分组的信息

Group by, Count and Lambda Expression

关于mysql - 需要帮助解决SQL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35560239/

10-10 00:05
查看更多