2

在此处输入图像描述

这是我的数据。我想取 6 行,但我希望 all HeadlineCategoryId's 在我的结果列表中是唯一的。如果我选择前 6 个,我将从HeadlineCategoryID20 (6,2) 中取出 2 行。你有什么建议吗?

4

2 回答 2

2
SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  HeadlineCategoryID, MAX(Creation) max_date
            FROM    TableName
            GROUP   BY HeadlineCategoryID
        ) b ON  a.HeadlineCategoryID = b.HeadlineCategoryID AND
                a.Creation = b.max_date
ORDER   BY a.Creation DESC  -- << specify here how are you going to sort
LIMIT   6                   --    the records you want to get 

更新 1

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  HeadlineCategoryID, MAX(NewsID) max_id
            FROM    TableName
            GROUP   BY HeadlineCategoryID
        ) b ON  a.HeadlineCategoryID = b.HeadlineCategoryID AND
                a.NewsID = b.max_id
ORDER   BY a.Creation DESC  -- << specify here how are you going to sort
LIMIT   6                   --    the records you want to get 
于 2013-05-07T13:44:46.603 回答
0

看起来您想要最近的六条记录,但 HeadlineCategoryId 是唯一的。如果是这样,这将起作用:

select top 6 NewsId, Creation, HeadlineCategoryId
from (select t.*,
             row_number() over (partition by HeadlineCategoryId order by Creation desc) as seqnum
      from t
     ) t
where seqnum = 1

作为注释。. . 这个问题最初表明它使用的是 SQL Server,而不是 MySQL。MySQL 中的解决方案并不那么简单。这是一种方法not exists

select NewsId, Creation, HeadlineCategoryId
from t
where not exists (select 1
                  from t t2
                  where t2.HeadlineCategoryId = t.HeadlineCategoryId and
                        t2.id < t.id)
limit 6

not exists部分是说“对于给定的标题类别,没有其他具有更大 id 的记录”。

于 2013-05-07T13:44:16.403 回答