重复选择行甚至是不同的

时间:2014-08-05 22:32:20

标签: sql-server inner-join

我有三个内连接表,当我选择它返回重复行我使用distict仍然返回重复行

TABLE [dbo].[Tbl_Comment](
[Comid] [int] IDENTITY(1,1) NOT NULL,
[bookid] [int] NULL,
[U_ID] [int] NULL,
[Comment] [nvarchar](max) NULL,
[Com_date] [datetime] NULL,
[puplished] [bit] NULL,
CONSTRAINT [PK_Tbl_Comment] PRIMARY KEY CLUSTERED 

第二个表是

TABLE [dbo].[Tbl_Reply](
[replyid] [int] IDENTITY(1,1) NOT NULL,
[Comid] [int] NULL,
[U_ID] [int] NULL,
[replymsg] [nvarchar](max) NULL,
[rep_datetime] [datetime] NULL,
[is_deleted] [bit] NULL,
CONSTRAINT [PK_Tbl_Reply] PRIMARY KEY CLUSTERED 

我的最后一个是

TABLE [dbo].[Tbl_adminreply](
[adrep_id] [int] IDENTITY(1,1) NOT NULL,
[Comid] [int] NULL,
[adminreply] [nvarchar](max) NULL,
CONSTRAINT [PK_Tbi_adminreply] PRIMARY KEY CLUSTERED 

表回复和Tbl_adminreply通过comid与注释表连接 当我选择它返回重复行?

SELECT  DISTINCT  Tbl_Comment.Comment, Tbl_Reply.replymsg,   Tbl_Reply.rep_datetime, Tbl_adminreply.adminreply
FROM Tbl_adminreply 
INNER JOIN Tbl_Comment ON Tbl_adminreply.Comid = Tbl_Comment.Comid 
INNER JOIN Tbl_Reply ON Tbl_Comment.Comid = Tbl_Reply.Comid  
WHERE (Tbl_Comment.Comid = 3) ORDER BY Tbl_Reply.rep_datetime DESC

2 个答案:

答案 0 :(得分:0)

试试这个......

SELECT A.Comment
      ,A.replymsg
      ,A.rep_datetime
      ,A.adminreply
FROM (
        SELECT    Tbl_Comment.Comment
                , Tbl_Reply.replymsg
                , Tbl_Reply.rep_datetime
                , Tbl_adminreply.adminreply
                , ROW_NUMBER() OVER (PARTITION BY Tbl_Comment.Comid ORDER BY Tbl_Reply.rep_datetime DESC) rn
        FROM Tbl_adminreply 
        INNER JOIN Tbl_Comment    ON Tbl_adminreply.Comid = Tbl_Comment.Comid 
        INNER JOIN Tbl_Reply      ON Tbl_Comment.Comid    = Tbl_Reply.Comid  
        WHERE      Tbl_Comment.Comid = 3 
      ) A
WHERE A.rn = 1
ORDER BY A.rep_datetime DESC

答案 1 :(得分:0)

如果是MS-SQL Server

请使用row_Number()检查参考此http://msdn.microsoft.com/en-GB/library/ms186734.aspx

让我们知道它是否有效

WITH Result AS
(
 SELECT c.Comment, r.replymsg,   r.rep_datetime, a.adminreply,
    ROW_NUMBER()OVER (PARTITION BY a.Comid ORDER BY a.Comid, r.rep_datetime) AS ROW_NO
    FROM Tbl_adminreply a
    INNER JOIN Tbl_Comment c ON a.Comid = c.Comid 
    INNER JOIN Tbl_Reply r ON c.Comid = r.Comid  
    WHERE c.Comid = 3
 )

 SELECT Comment, replymsg, rep_datetime, adminreply
 FROM Result where Result.ROW_NO > 2;