从一个表中选择2个时间记录

时间:2015-06-01 07:22:24

标签: sql sql-server sql-server-2012

我有2张如下表

PostList: post_id(PK,Identity)

LikeList: like_id(PK,Identity), post_id(FK)

LikeList中的每个帖子都是喜欢的。

此任务类似于FaceBook上的帖子

当DataList绑定时,我从.cs传递2个值 无论post_id和当前用户ID(mid

  1. 计算每个帖子。
  2. 如果当前用户alredy喜欢,则更改按钮文字与
  3. 不同

    我创建了像

    这样的查询
    SELECT mid
    ,(SELECT COUNT(post_id) FROM LikeList WHERE post_id=@sp_post_id) as like_count
    FROM LikeList WHERE (post_id=@sp_post_id AND mid=@sp_mid) 
    GROUP BY mid
    

    我得到了post_id次,但在past post_id=27user/mid=2的情况下 PostList显然我们没有找到记录。

    我想要的:检查帖子喜欢计数,检查用户是否喜欢这篇文章。 (我如何检查计数和当前用户是否喜欢?)

    表数据:

    post_id fid mid post_img post_msg post_time 1 1 1 Tulips.jpg this post from user1. 2015-05-26 3 3 2 Lighthouse.jpg this post from user2. 2015-05-26 5 1002 3 road1.jpg this post from user3. 2015-05-26 6 3 2 map1.jpg this 2 post from user2. 2015-05-27 7 1 1 This is text Post From User1 2015-05-27 26 1 1 globe.jpg 2015-05-28 27 1003 5 Gujarat.jpg this post from user5, again. 2015-05-29 30 3 2 Location2.jpg post from user2 2015-05-29

    LikeList

    like_id post_id mid like_status like_time 1 27 1 1 2015-05-29 2 30 1 1 2015-05-29 3 6 1 1 2015-05-29 4 30 2 1 2015-05-29 9 6 2 1 2015-05-29

    Sub vignesh()
    Dim StartChar As Integer, _
        LenColor As Integer
    
    For i = 1 To 5
        With Sheets("Sheet1").Cells(i, 1)
            StartChar = InStr(1, .Value, "|")
            If StartChar <> 0 Then
                LenColor = Len(.Value) - StartChar + 1
                .Characters(Start:=StartChar, Length:=LenColor).Font.Color = RGB(255, 0, 0)
            End If
        End With
    Next i
    
    End Sub
    

    会发生什么: 用户在线时:mid = 1

    post_id:30次喜欢2次(在线用户也喜欢)

    当用户在线时:mid = 2

    post_id:27次赞1次(在线用户不喜欢)

1 个答案:

答案 0 :(得分:1)

SELECT 
    post_id, 
    COUNT(*) AS LikeCount,
    MAX(CASE mid WHEN @sp_mid THEN 1 ELSE 0 END) AS UserLiked -- 0 for No; 1 for Yes
FROM LikeList 
WHERE 1 = 1
    AND post_id = @sp_post_id -- You can comment this line for viewing all post
    AND like_status = 1
GROUP BY post_id