这是我的数据。我想要6行,但我希望所有HeadlineCategoryId
在我的结果列表中都是唯一的。如果我选择前6名,我会从HeadlineCategoryID
20(6,2)中选择2行。你有什么建议吗?
答案 0 :(得分: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
答案 1 :(得分: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”。