2012-04-10 127 views
3

我不能得到这个SQL查询的权利...SELECT DISTINCT TOP 5在SQL Server

我想从tblComment前5的最新评论。问题是我得到的评论和ProductID相同。我不想那样。

SELECT DISTINCT TOP 5 
    tblProduct.ProductID, 
    tblProduct.ProductName, 
    tblComment.DateAdded 
FROM 
    tblComment 
INNER JOIN 
    tblProduct ON tblProduct.ProductID = tblComment.ProductID 
ORDER BY 
    tblComment.DateAdded DESC 

我在做什么错?

+1

因此,有五种不同的产品,并且您希望每个产品的最新评论? – 2012-04-10 17:59:23

+0

这是一对多连接。你会得到很多行:)在这里看看这个问题:http://stackoverflow.com/questions/6922675/how-to-select-unique-rows-from-one-to-many-relationed-tables-in-mysql – PhD 2012-04-10 17:59:25

+0

有数以百计的产品,我想要加入最近有评论的前5名产品。即使一件产品有最新的五条评论,我也不会因此而想要该产品五次。我需要五个不同的产品。 – user1007103 2012-04-10 18:04:30

回答

6

假设你的评语表有一个ID字段尝试这个办法:通过最新的评论的时候排名

​​3210
+1

+1最干净的答案,加入最大值。 – Taryn 2012-04-10 18:12:18

+0

工程太棒了!非常感谢! – user1007103 2012-04-10 18:14:10

0

您将不得不子选择 - 使用下面的示例来满足您的需求。

SELECT TOP 5 tblProduct.ProductID, 
      tblProduct.ProductName, 
      tblComment.DateAdded 
FROM tblComment INNER JOIN 
    tblProduct ON tblProduct.ProductID = tblComment.ProductID 
    and tblProduct.ProductID 
     IN (
      SELECT tblProduct.ProductID 
      FROM tblComment 
        INNER JOIN tblProduct ON tblProduct.ProductID = tblComment.ProductID 
      GROUP BY tblProduct.ProductID 
      HAVING count(tblProduct.ProductID ) =1 
     ) 
0

产品。

该方法使用CTE和秩函数。这个查询很小,但在较大的查询中,这些函数可以使事情更有组织性和可读性。

with lastComment as (
    select c.productID, max(DateAdded) DateAdded, 
    row_number() over(order by max(dateAdded)) rank 
    from tblComment c 
    group by c.productID 

) 

SELECT 
    tblProduct.ProductID, 
    tblProduct.ProductName, 
    tblComment.DateAdded 
FROM 
    tblProduct 
    join lastComment ON tblProduct.ProductID = lastCommnet.ProductID 
WHERE 
    lastComment.rank >= 5 
ORDER BY lastComment.rank