0

我是 SQL Server 的新手,我的一个 SQL 查询需要帮助。

我有 2 张桌子(RatingLikeDislike)。

我正在尝试使用LEFT JOIN这样的方法从这两个表中获取数据:

SELECT 
   R.ID, R.Topic, R.CountLikes, R.CountDisLikes, R.Extra, LD.UserName, LD.Clikes
FROM 
   Rating As R
LEFT JOIN 
   LikeDislike AS LD ON LD.TopicID = R.ID
ORDER BY 
   R.ID DESC

上面的SELECT语句显示结果很好,但也包括重复项。我想在显示数据时删除重复项,我尝试使用DISTINCTand GROUP BY,但没有运气,可能是因为我没有正确使用它。

更新:为了更清楚和更少混淆,让我告诉你每个表的确切作用以及我想要实现的目标。

Rating表包含以下列 ( ID, Topic, CountLikes, CountDisLikes, Extra, CreatedByUser)。它存储每个主题以及UserID创建该主题的用户的主题信息和喜欢和不喜欢的数量。

LikeDisLike表包含以下列 ( ID, TopicID, UserName, Clikes)。是表中列TopicID的 FK 。IDRating

现在我要做的是从这两个表中获取信息,而不需要重复的行。我需要从Rating表+中获取所有列的数据,UserNameClikesLikeDislike表中获取所有列,而不需要任何重复的行

更新 2:
以下是此 SELECT 语句重复的结果:

SELECT  
   DISTINCT ld.TopicID, R.ID, R.Topic, R.CountLikes, R.CountDisLikes, 
   LD.UserName, LD.Clikes 
FROM 
   Rating AS R 
LEFT JOIN 
   LikeDislike AS LD ON  LD.TopicID = R.ID

结果输出:

TopicID ID  Topic            CountLikes   CountDislikes UserName    Clikes
NULL    79  Testing at home    1           0             NULL       NULL
NULL    80  Testing at home2   1           0             NULL       NULL 
NULL    82  testing dislikes   0           1             NULL       NULL
1       1   Do You Like This   211         58            3          FALSE
2       2   Or This            17          25            3          TRUE
76      76  Testing part 3     7           5             2          FALSE
76      76  Testing part 3     7           5             3          FALSE
77      77  Testing part 4     16          6             2          TRUE
77      77  Testing part 4     16          6             3          TRUE
77      77  Testing part 4     16          6             5          TRUE
4

3 回答 3

2

以下语法应删除完整的重复项:

SELECT distinct R.ID, R.Topic, R.CountLikes, R.CountDisLikes, R.Extra,
       LD.UserName, LD.Clikes
FROM Rating As R
LEFT JOIN LikeDislike AS LD on LD.TopicID = R.ID
ORDER BY R.ID desc

这是你试过的吗?

于 2013-01-18T03:03:06.793 回答
0

我认为这种方式将为您提供正确的输出

select ID, Topic,CountLikes,CountDisLikes,Extra,
   UserName, Clikes from (
    SELECT distinct R.ID, R.Topic, R.CountLikes, R.CountDisLikes, R.Extra,
   LD.UserName, LD.Clikes
            , ROW_NUMBER() over (partition by R.ID order by R.ID desc) as rid
   FROM Rating As R
    LEFT JOIN LikeDislike AS LD on LD.TopicID = R.ID
    ORDER BY R.ID desc) t where rid=1 order by ID desc

否则请检查likedislike tbl,您在其中插入2个主题以获得相同的评级tbl id,并检查用户名,Clikes也检查它们在likedislike tbl中是否相似

于 2013-01-18T05:39:38.537 回答
0

尝试这个

        SELECT R.ID, R.Topic, R.CountLikes, R.CountDisLikes, R.Extra, 
LD.UserName, LD.Clikes  FROM Rating AS R 
        Left Join ( SELECT TopicID, UserName, min(Clikes) as Clikes 
    From LikeDisLike Group by TopicID,UserName) AS LD 
on R.ID = LD.TopicID ORDER By R.ID Desc

顺便说一句,我认为您需要 UNIQUE(TopicID,UserName) 约束来避免重复。

于 2013-01-18T06:42:00.673 回答