0

我有以下表格:

用户、节拍、流量、节拍_喜欢_不喜欢、流量_喜欢_不喜欢。这是关系。

用户 UserID 是一个主键,与 Beats 和 FLow 的 UserID 外键都有关系。Beats BeatID 与 Beats_Likes_Dislikes BeatID 有关系。它与流及其 like_dislike 表相同。我需要将 Beats 和 Flows 中的 Likes 总结为 Likes,将两个表中的 Dislikes 总结为 Dislikes。我有以下内容:

SELECT
ISNULL(SUM(Beats_Likes_Dislikes.[Like]) , 0) AS Likes, 
-- + ISNULL(SUM(Flows_Likes_Dislikes.[Like]), 0) AS Likes,
ISNULL(SUM(Beats_Likes_Dislikes.Dislike), 0) AS DisLikes 
-- + ISNULL(SUM(Flows_Likes_Dislikes.DisLike), 0) AS DisLikes
From Users 
INNER JOIN Beats 
ON Users.UserID = Beats.UserID
INNER JOIN Beats_Likes_Dislikes ON Beats.BeatID= Beats_Likes_Dislikes.BeatID
--INNER JOIN Flows ON Users.UserID = Flows.UserID
--INNER JOIN Flows_Likes_Dislikes ON Flows.FlowID=Flows_Likes_Dislikes.FlowID
Where Users.UserID = '110'

这很好地返回了节拍的喜欢和不喜欢(单独的行)的总和。我需要从流表中获取相同的数据。您会看到我已经注释掉了流表的部分,因为数字没有相加。我在这里做错了什么?

谢谢。

4

3 回答 3

1

由于无意的多对多连接,您的号码可能会关闭。例如,每个独特的用户可以有多个节拍,每个独特的节拍可以有多个喜欢或不喜欢。没关系,但是如果您随后尝试水平连接另一组表,您最终会创建太多行,因为每个用户/流/流率对的 ON 条件不止一次。

要纠正这个问题,您可能需要分成 2 个查询,然后加入结果

select 
coalesce(beat_likes,0)+coalesce(flow_likes,0) as total_likes,
coalesce(beat_dislikes,0)+coalesce(flow_dislikes,0) as total_dislikes
FROM
(    
SELECT 
u.UserID,
SUM(bld.Like) as beat_likes,
SUM(bld.Dislike) as beat_dislikes 
From Users u
    INNER JOIN Beats b
    ON u.UserID = b.UserID
        INNER JOIN Beats_Likes_Dislikes bld
        ON b.BeatID= bld.BeatID
Where u.UserID = '110'
GROUP BY u.UserID
) t1
JOIN 
(
SELECT 
u.UserID,
SUM(fld.Like) as flow_likes,
SUM(fld.Dislike) as flow_dislikes 
From Users u
    INNER JOIN Flows f
    ON u.UserID = f.UserID
        INNER JOIN Flows_Likes_Dislikes fld
        ON f.FlowID= fld.FlowID
Where u.UserID = '110'
GROUP BY u.UserID
) t2
on t1.UserID =t2.UserID
于 2012-04-18T03:03:32.553 回答
0

根据您的具体要求,您可能需要使用 LEFT OUTER JOIN 而不是 INNER JOIN。 加入类型的信息......这就是为什么你的号码是关闭的。

于 2012-04-18T02:51:54.503 回答
0

试试这个:

SELECT SUM(likes) as totalLikes, 
       SUM(dislikes) as totalDislikes 
  FROM (SELECT Isnull(SUM(beats_likes_dislikes.[Like]), 0)  AS likes, 
               Isnull(SUM(beats_likes_dislikes.dislike), 0) AS dislikes 
          FROM users 
         INNER JOIN beats 
               ON users.userid = beats.userid 
         INNER JOIN beats_likes_dislikes 
               ON beats.beatid = beats_likes_dislikes.beatid 
        WHERE  users.userid = '110' 

        UNION ALL 

        SELECT Isnull(SUM(flows_likes_dislikes.[Like]), 0)  AS likes, 
               Isnull(SUM(flows_likes_dislikes.dislike), 0) AS dislikes 
          FROM users 
         INNER JOIN flows 
               ON users.userid = flows.userid 
         INNER JOIN flows_likes_dislikes 
               ON flows.flowid = flows_likes_dislikes.flowid 
         WHERE users.userid = '110') AS t 

它应该为您提供用户的总喜欢和不喜欢。

于 2012-04-18T02:59:17.390 回答