【问题标题】:Need help in solving SQL需要帮助解决 SQL
【发布时间】:2016-02-22 17:38:43
【问题描述】:

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

我有 3 张桌子

用户

用户名 -用户名 -电子邮件 -密码 -姓名 -个人资料图片

发帖

-Postid -Content -Postdate -Userid

好友列表

Friendlistid - userid -friendid -status

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

这是我的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代码有什么解决办法吗?

【问题讨论】:

  • 您需要多个查询。
  • 不要以纯文本形式存储密码

标签: mysql linq


【解决方案1】:

如果您在表之间存在关系并且正在使用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

【讨论】:

    猜你喜欢
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    相关资源
    最近更新 更多