Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

mysql

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.

How to write this SQL?

like image 721
Keyne Viana Avatar asked Apr 07 '10 05:04

Keyne Viana


People also ask

How do I select a certain number of rows?

Select one or more rows and columns Or click on any cell in the column and then press Ctrl + Space. Select the row number to select the entire row. Or click on any cell in the row and then press Shift + Space. To select non-adjacent rows or columns, hold Ctrl and select the row or column numbers.

How do I limit the number of rows returned?

You use the LIMIT clause to constrain the number of rows returned by the query. For example, a SELECT statement may return one million rows. However, if you just need the first 10 rows in the result set, you can add the LIMIT clause to the SELECT statement to retrieve 10 rows.

How do I select a limited row in SQL Server?

If you don't need to omit any rows, you can use SQL Server's TOP clause to limit the rows returned. It is placed immediately after SELECT. The TOP keyword is followed by integer indicating the number of rows to return. In our example, we ordered by price and then limited the returned rows to 3.

How do I select only few rows in mysql?

The following is the syntax to get the last 10 records from the table. Here, we have used LIMIT clause. SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query.


1 Answers

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.

like image 172
OMG Ponies Avatar answered Nov 01 '22 13:11

OMG Ponies