如何根据一个表中列中的唯一性值从2个表中进行选择

时间:2012-02-05 15:04:07

标签: c# asp.net sql

我有2张桌子: 第一(案例) 第二(评论)

一对多的关系;我将每个案例的评论存储在评论表中。

我需要从案例表中选择案例信息,这些案例信息显示在评论表中,但我希望每个案例都按照评论添加日期(cDate)的顺序显示

我试过了:

SELECT TOP 10  
     Cases.*,  
     comments.cDate  
FROM  
     Cases 
INNER JOIN comments 
     ON Cases.Case_ID = comments.Case_ID 
WHERE comments.Case_ID IN 
        (
           SELECT DISTINCT 
              Case_ID 
           FROM 
             comments
         ) 
 ORDER BY cDate DESC

但如果它有很多评论,它会多次检索案例。我需要它只出现一次


谢谢大家,你们帮助了很多, 我刚刚添加了

Cases.Case_ID IN (SELECT Case_ID FROM comments) 

它完美无缺。

Select语句现在就是这样:

SELECT top 10 Cases.*,
(SELECT MAX(comments.cDate) 
       FROM comments 
       WHERE Cases.Case_ID = comments.Case_ID  ) AS cDate 
FROM Cases
WHERE Cases.Case_ID 
                 IN (SELECT Case_ID FROM comments) 
ORDER BY cDate DESC 

再次感谢:)

4 个答案:

答案 0 :(得分:1)

在这种情况下,看起来您想要使用子查询:

SELECT top 10 Cases.*, 
(SELECT MAX(comments.cDate) FROM comments 
           WHERE Cases.Case_ID = comments.Case_ID ) AS cDate
FROM Cases 
ORDER BY cDate DESC    

答案 1 :(得分:1)

这样做:

SELECT TOP 10
        A.* ,
        (SELECT MAX(C.cDate) FROM comments C WHERE C.Case_ID = A.Case_ID) commDate
FROM    Cases A
        INNER JOIN comments B ON A.Case_ID = B.Case_ID
ORDER BY commDate

(@ yhw42查询将返回没有评论的案例。)

答案 2 :(得分:0)

首先是一些测试数据:

DECLARE @tblCases TABLE(Case_ID INT)
DECLARE @comments TABLE(Case_ID INT,cDate DATETIME)

INSERT INTO @tblCases
SELECT 1 UNION ALL SELECT 2

INSERT INTO @comments
SELECT 1,GETDATE() UNION ALL
SELECT 1,GETDATE()-1 UNION ALL
SELECT 2,GETDATE()-2 UNION ALL
SELECT 2,GETDATE()-3

然后我会这样做。

;WITH CTE AS
(
    SELECT
        RANK() OVER(PARTITION BY Case_ID ORDER BY cDate DESC) AS iRank,
        tbl.cDate,
        tbl.Case_ID
    FROM
        @comments AS tbl
)
SELECT TOP 10  
     Cases.*,  
     CTE.cDate  
FROM  
    CTE
    JOIN @tblCases AS Cases
        ON Cases.Case_ID=CTE.Case_ID
WHERE
    CTE.iRank=1

答案 3 :(得分:0)

谢谢大家,你帮了很多,我刚刚补充了

Cases.Case_ID IN (SELECT Case_ID FROM comments) 

它完美无缺。

Select语句现在就是这样:

SELECT top 10 Cases.*,
(SELECT MAX(comments.cDate) 
       FROM comments 
       WHERE Cases.Case_ID = comments.Case_ID  ) AS cDate 
FROM Cases
WHERE Cases.Case_ID 
                 IN (SELECT Case_ID FROM comments) 
ORDER BY cDate DESC 

再次感谢:)