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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With