MySql查询:从表中为每个类别选择前3行

时间:2010-06-29 12:31:14

标签: mysql view limit

我有一个包含记录的表,它有一行名为category。我插入了太多文章,我想从每个类别中只选择两篇文章。

我试着这样做:

我创建了一个视图:

CREATE VIEW limitrows AS 
   SELECT * FROM tbl_artikujt ORDER BY articleid DESC LIMIT 2 

然后我创建了这个查询:

SELECT * 
FROM tbl_artikujt 
WHERE 
   artikullid IN
   (
      SELECT artikullid
      FROM limitrows
      ORDER BY category DESC
   )
ORDER BY category DESC;

但这不起作用,只给我两个记录?

4 个答案:

答案 0 :(得分:11)

LIMIT仅停止语句返回的结果数。您正在寻找的通常称为分析/窗口/排名功能 - MySQL不支持但您可以使用变量进行模拟:

SELECT x.*
  FROM (SELECT t.*,
               CASE 
                 WHEN @category != t.category THEN @rownum := 1 
                 ELSE @rownum := @rownum + 1 
               END AS rank,
               @category := t.category AS var_category
          FROM TBL_ARTIKUJT t
          JOIN (SELECT @rownum := NULL, @category := '') r
      ORDER BY t.category) x
 WHERE x.rank <= 3

如果您不更改SELECT x.*,结果集将包含rankvar_category值 - 如果不是,则必须指定您真正想要的列案件。

答案 1 :(得分:2)

阅读这篇文章:Top N of a group

答案 2 :(得分:0)

SELECT * FROM (   
    SELECT  VD.`cat_id` ,  
       @cat_count := IF( (@cat_id = VD.`cat_id`), @cat_count + 1, 1 ) AS 'DUMMY1', 
       @cat_id := VD.`cat_id` AS 'DUMMY2',
       @cat_count AS 'CAT_COUNT'   
     FROM videos VD   
     INNER JOIN categories CT ON CT.`cat_id` = VD.`cat_id`  
       ,(SELECT @cat_count :=1, @cat_id :=-1) AS CID  
     ORDER BY VD.`cat_id` ASC ) AS `CAT_DETAILS`
     WHERE `CAT_COUNT` < 4

------- STEP FOLLOW ----------  
1 . select * from ( 'FILTER_DATA_HERE' ) WHERE 'COLUMN_COUNT_CONDITION_HERE' 
2.  'FILTER_DATA_HERE'   
    1. pass 2 variable @cat_count=1 and  @cat_id = -1  
    2.  If (@cat_id "match" column_cat_id value)  
        Then  @cat_count = @cat_count + 1    
        ELSE @cat_count = 1      
    3. SET @cat_id = column_cat_id    

 3. 'COLUMN_COUNT_CONDITION_HERE'   
    1. count_column < count_number    

4. ' EXTRA THING '
   1. If you want to execute more than one statement inside " if stmt "
   2. IF(condition, stmt1 , stmt2 )
      1. stmt1 :- CONCAT(exp1, exp2, exp3) 
      2. stmt2 :- CONCAT(exp1, exp2, exp3) 
   3. Final "If" Stmt LIKE 
      1. IF ( condition , CONCAT(exp1, exp2, exp3) , CONCAT(exp1, exp2, exp3) )    
share

答案 3 :(得分:-4)

使用group by而不是order by。