将一列加入两个表

时间:2014-08-28 17:13:15

标签: sql sql-server tsql

我有一个数据库,其中包含帐户,帖子以及用户喜欢的帖子的信息。

AccountData
id || username

PostData
id || text || accountid

LikesDislikesData
liked(bool) || accountid || postid

我有一个视图设置,因为我需要来自数据库的特定数据绑定到我的应用程序内部。这是我正在使用的代码:

  SELECT trippin.PostData.id, trippin.AccountData.username, trippin.PostData.posttext,     
    trippin.CategoryData.categoryname, trippin.PostData.__createdat as CreatedAt,
    SUM(CASE WHEN likes.liked = 1 THEN 1 ELSE 0 END) as Likes, 
    SUM(CASE WHEN likes.liked = 0 THEN 1 ELSE 0 END) as DisLikes
FROM trippin.PostData    
INNER JOIN trippin.AccountData ON trippin.PostData.accountid = trippin.AccountData.id
INNER JOIN trippin.CategoryData ON trippin.CategoryData.id = trippin.PostData.categoryid
LEFT OUTER JOIN trippin.LikesDislikesData likes ON likes.postid = trippin.PostData.id
GROUP BY (trippin.AccountData.username), (trippin.PostData.posttext), (trippin.PostData.id), (trippin.categorydata.categoryname), (trippin.PostData.__createdat)

问题在于,每当我向(likes.accountid = trippin.AccountData.id)添加连接时,行都会重复或输出不正确。

我认为这可能是一个设计问题,但我不确定,也找不到任何可以解决我确切问题的事情。

基本上,每个帖子都是由用户制作的。然后,其他用户喜欢或不喜欢(或没有)每个帖子。我需要在视图中包含所有这些数据,以便将其传递给我的应用程序。

1 个答案:

答案 0 :(得分:1)

select postID
  , sum(case when liked = true then 1 else 0 end) as liked
  , sum(case when liked = true then 1 else 0 end) as disliked
from trippin.LikesDislikesData
group by postID

以上陈述应该通过帖子ID给你喜欢和不喜欢。称之为子查询并加入您的主要:

SELECT trippin.PostData.id, trippin.AccountData.username, trippin.PostData.posttext,     
trippin.CategoryData.categoryname, trippin.PostData.__createdat as CreatedAt,
Likes, 
DisLikes
FROM trippin.PostData    
INNER JOIN trippin.AccountData ON trippin.PostData.accountid = trippin.AccountData.id
INNER JOIN trippin.CategoryData ON trippin.CategoryData.id = trippin.PostData.categoryid
LEFT OUTER JOIN   (
  select postID
  , sum(case when liked = true then 1 else 0 end) as liked
  , sum(case when liked = true then 1 else 0 end) as disliked
from trippin.LikesDislikesData
group by postID)
likes ON likes.postid = trippin.PostData.id

应该为你所追求的目标而努力。我删除了你的group by子句,因为你不再需要sums语法。通常你会发现创建一个子查询来按ID进行计数和求和,并通过该ID将其连接到主查询将是获取计数的最简单的解决方案...至少不必按整个select语句进行分组