通过特定键的范围限制mysql结果包括重复项

时间:2013-10-22 03:55:18

标签: mysql sql

我有一个查询

SELECT p.*, m.*,
  (SELECT COUNT(*) FROM newPhotoonAlert n WHERE n.userIDfor='$id' AND n.threadID=p.threadID and n.seen='0')  AS unReadCount 
    FROM posts p
    JOIN myMembers m ON m.id = p.user_id
    LEFT JOIN following f 
    ON (p.user_id = f.user_id AND f.follower_id='$id' 
    AND f.request='0' AND f.status='1')
    JOIN myMembers searcher ON searcher.id = '$id' 
    WHERE ((f.follower_id = searcher.id) OR m.id='$id')
    AND p.flagged <'5' 
    ORDER BY p.threadID DESC,p.positionID

它会带来预期的结果,但我想添加Another CLAUSE来限制结果。 使用上述查询说一个示例(最小显示)数据集如下所示。

threadID   postID positionID  url
  564       1254     2         a.com
  564       1245     1         a1.com
  541       1215     3         b1.com 
  541       1212     2         b2.com 
  541       1210     1         b3.com 
  523       745      1         c1.com
  435       689      2         d2.com
  435       688      1         a4.com
  256       345      1         s3.com
  164       316      1         f1.com
  .
  .

我希望ROWS对应于从MAX开始的2个DISTINCT threadID,但我也希望包含重复项。

这样的东西
AND p.threadID IN (Select just Two of all threadIDs currently selected, but include duplicate rows)

所以我的结果应该是

threadID   postID positionID  url
  564       1254     2         a.com
  564       1245     1         a1.com
  541       1215     3         b1.com 
  541       1212     2         b2.com 
  541       1210     1         b3.com 

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

select threadID, postID, positionID, url 
from your_table where 
threadID in
(select * from (select distinct threadID from your_table order by threadID desc limit 10) as tab_alias);

尝试使用此语法来实现它。