Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL LIMIT before Grouping?

I want to LIMIT Grouped results to 30, but instead I'm grouping all rows and then limiting it to 30 groups. How do I do the opposite?

SELECT *, COUNT(*) AS COUNT FROM `Posts` GROUP By `Category` LIMIT 30
like image 780
lisovaccaro Avatar asked Feb 25 '12 06:02

lisovaccaro


People also ask

Does limit come before or after group by?

The ORDER BY clause goes after the FROM clause but before the LIMIT .

Can we use limit with group by?

No, you can't LIMIT subqueries arbitrarily (you can do it to a limited extent in newer MySQLs, but not for 5 results per group). This is a groupwise-maximum type query, which is not trivial to do in SQL.

Can we use ORDER BY before group by?

When combining the Group By and Order By clauses, it is important to bear in mind that, in terms of placement within a SELECT statement: The GROUP BY clause is placed after the WHERE clause. The GROUP BY clause is placed before the ORDER BY clause.

Is there a limit clause in MySQL?

The MySQL LIMIT ClauseThe LIMIT clause is used to specify the number of records to return. The LIMIT clause is useful on large tables with thousands of records. Returning a large number of records can impact performance.


1 Answers

SELECT *, COUNT(*) AS COUNT FROM (SELECT * FROM `Posts` LIMIT 30) t GROUP By `Category`
like image 134
Vadim Avatar answered Oct 11 '22 08:10

Vadim