关于时间轴的SQL查询喜欢(SQL query about timeline likes)

编程入门 行业动态 更新时间:2024-10-10 01:18:19
关于时间轴的SQL查询喜欢(SQL query about timeline likes)

我正在写类似于Facebook时间线的内容,用户可以看到所有帖子,如果用户之前喜欢过该帖子,也会看到蓝色拇指。

这是两张桌子,

Posts PostID | USERID | MORE COLS.... 1 | 1 | .... 2 | 1 | .... 3 | 3 | .... 4 | 5 | .... Likes LikeID | POSTID | USERID | MORE COLS.... 1 | 1 | 1 | .... 2 | 1 | 5 | .... 3 | 2 | 1 | .... 4 | 3 | 6 | ....

我的问题是,我如何编写一个SQL查询来获取所有帖子,并知道用户以前是否喜欢这些帖子?

因此,例如,查询的理想结果将是(如果此用户的id为1)

All Posts PostID | LikedByMeBefore | .... 1 | true | .... 2 | false | .... 3 | true | .... 4 | true | .... 5 | false | .... 6 | false | .... . | . | .... . | . | ....

I'm writing something similar to facebook timeline that user can see all the post and also see a blue thumb if the user has liked that post before.

Here are the two tables,

Posts PostID | USERID | MORE COLS.... 1 | 1 | .... 2 | 1 | .... 3 | 3 | .... 4 | 5 | .... Likes LikeID | POSTID | USERID | MORE COLS.... 1 | 1 | 1 | .... 2 | 1 | 5 | .... 3 | 2 | 1 | .... 4 | 3 | 6 | ....

My question is that how can I write a sql query to get all the posts and also know if the user has liked these posts before?

So for example the ideal result of the query would be like (if this user's id is 1)

All Posts PostID | LikedByMeBefore | .... 1 | true | .... 2 | false | .... 3 | true | .... 4 | true | .... 5 | false | .... 6 | false | .... . | . | .... . | . | ....

最满意答案

目前还不清楚Posts表中的UserID列是什么,但我可以假设它是创建它的用户。 但是Likes表中的UserID更加明显。 你需要使用LEFT JOIN结合ISNULL :

DECLARE @UserID INT = 5 SELECT Posts.PostID, ISNULL(Likes.LikeID, 0) AS LikedByMeBefore, ...more columns... FROM Posts LEFT JOIN Likes ON Posts.PostID = Likes.PostID AND (Likes.UserID = @UserID OR Likes.UserID IS NULL)

It's unclear what the UserID column is in the Posts table, but I can assume it's the user who created it. The UserID in the Likes table is more obvious though. You need to use a LEFT JOIN combined with ISNULL:

DECLARE @UserID INT = 5 SELECT Posts.PostID, ISNULL(Likes.LikeID, 0) AS LikedByMeBefore, ...more columns... FROM Posts LEFT JOIN Likes ON Posts.PostID = Likes.PostID AND (Likes.UserID = @UserID OR Likes.UserID IS NULL)

更多推荐

本文发布于:2023-04-29 02:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1334431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间   喜欢   SQL   likes   query

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!