How to select a limited amount of rows for each foreign key?

前端 未结 4 796
忘掉有多难
忘掉有多难 2021-01-06 10:19

I have this table:

id
feed_id
...

Let\'s say that I have 500 rows and I want to select 3 entries for each feed_id? And 50 as total limit.

相关标签:
4条回答
  • 2021-01-06 10:28

    Use:

    SELECT x.feedid
      FROM (SELECT t.feedid,
                   CASE WHEN @feed != t.feedid THEN @rownum := 1 ELSE @rownum := @rownum + 1 END AS rank,
                   @feed := t.feedid
              FROM TABLE t
              JOIN (SELECT @rownum := NULL, @feed := 0) r
          ORDER BY t.feedid) x
     WHERE x.rank <= 3
     ORDER BY x.feedid
     LIMIT 50
    

    What's not clear is the details of what you want returned - all the rows in your table, or just the feedid.

    0 讨论(0)
  • 2021-01-06 10:30

    You can do this with help of stored procedure.

    DELIMITER $$
    CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_feed`()
    BEGIN
    DECLARE done INT DEFAULT 0;
    DECLARE a INT;
    DECLARE cur1 CURSOR FOR SELECT id FROM test.id LIMIT 50;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
    OPEN cur1;
    REPEAT
    FETCH cur1 INTO a;
        IF NOT done THEN
            SELECT * FROM feed_id WHERE id=a LIMIT 3;               
        END IF;
    UNTIL done END REPEAT;
    CLOSE cur1;
    
    END$$
    DELIMITER;
    
    0 讨论(0)
  • 2021-01-06 10:31

    In transact SQL you would use the TOP statement, not sure if that applies here ...

    0 讨论(0)
  • 2021-01-06 10:38

    Have you tried using a subselect and limit?

    Something like

    SELECT  *
    FROM    Table t
    WHERE   ID IN (SELECT ID FROM @Table WHERE FEED_ID = t.FEED_ID LIMIT 3)
    LIMIT 500
    
    0 讨论(0)
提交回复
热议问题