根据条件返回true或false作为自定义列

时间:2014-12-16 22:55:44

标签: sql sql-server

这可能很容易实现,但我之前没有这样做,我需要一些指导或帮助来实现这一目标。

我创建了一个存储过程并将UserId传递给过程。我必须修改我的查询并希望在查询中返回一个自定义列,该列将为true或'false'。无论用户是否对帖子进行了评论,都将确定是或否。所需查询的伪代码如下,

SELECT 
    a.Id, 
    a.Title, 
    a.Description, 
    b.Id, 
    b.Comment, 
    ['true' or 'false' as Commented based on whether User has commented for the respective post or not] 
from tbl_Posts a 
LEFT OUTER JOIN tbl_PostsComment 
    b ON a.Id = b.PostId

TABLES

tbl_Users
---------------
Id
Username
FirstName
LastName
Address


tbl_Posts
---------------
Id
Title
Description


tbl_PostsComment
------------------
Id
PostId
UserId
Comment

由于

编辑:

为了更好地解释问题,我将描述该场景。在我的网站中,当用户登录时,他们将看到所有帖子及其评论。因此,使用我上面发布的查询选择记录。现在他们是一个按钮,每个帖子都有“发表评论”。点击此用户将能够为任何相应的帖子发表评论,但前提是他尚未发表评论。

所以我想要做的就是像往常一样选择所有记录,但现在我将UserId传递给存储过程。所有帖子都将被选中,但是如果任何帖子用户已经给出了评论(如果该帖子的评论将出现在用户的UserId的tbl_PostsComment中),那么将返回true,否则将返回false。

2 个答案:

答案 0 :(得分:2)

也许这个会奏效:

SELECT
    a.Id,
    a.Title,
    a.Description,
    HasCommented = CASE WHEN COUNT(c.Id) > 0 THEN 'True' ELSE 'False' END
FROM tbl_Posts p
LEFT JOIN tbl_postsComment c
    on c.PostId = p.Id
    AND c.UserId = @userId
GROUP BY
    a.Id, a.Title, a.Description

答案 1 :(得分:0)

这是你正在寻找的吗?

SELECT a.Title, a.Description, b.ID, b.Comment CASE WHEN b.Comment IS NOT NULL THEN 1 ELSE 0 END AS [Commented]
FROM tbl_Posts a LEFT OUTER JOIN tbl_PostsComment b ON a.Id = b.PostId