Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql multiple limit in one sql statement

Tags:

php

mysql

I have table in my DB called "students" contains the following columns (student_id, student_name, year_of_birth).and array of years I trying to make one query that gets 10 student_id of each year in (years) array.

I could write

SELECT student_id FROM `students` WHERE year_of_birth=1950 LIMIT 10;
SELECT student_id FROM `students` WHERE year_of_birth=1951 LIMIT 10;
SELECT student_id FROM `students` WHERE year_of_birth=1952 LIMIT 10;
SELECT student_id FROM `students` WHERE year_of_birth=1953 LIMIT 10;
(and so on)

But that would be very time consuming Are there any other options Thank you

like image 886
dalia tarek Avatar asked Jan 17 '10 14:01

dalia tarek


People also ask

What is limit 2 1 SQL query?

The LIMIT clause is used in the SELECT statement to constrain the number of rows in a result set. The LIMIT clause accepts one or two arguments. The values of both arguments must be zero or positive integer constants. since you use negative(-1) number and hence that error is shown.

Can we use limit with group by in SQL?

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.

How do I limit a query in MySQL?

In MySQL the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments which are offset and count. The value of both the parameters can be zero or positive integers.

How do I SELECT multiple items in MySQL?

To select multiple values, you can use where clause with OR and IN operator.


1 Answers

This is also one of the example to find leap year with multiple limits

select year_n from the_years

select distinct month_n from the_months,the_years where year_n=$P{Year}

(select distinct day_n from the_days,the_months where $P{Month} IN('Jan','Mar','May','Jul','Aug','Oct','Dec') limit 31)
UNION ALL
(select distinct day_n from the_days,the_months where $P{Month} IN('Apr','Jun','Sep','Nov') limit 30)
UNION ALL
(select distinct day_n from the_days,the_years,the_months where $P{Month}='Feb' and mod($P{Year},4)!=0 or mod($P{Year},100)=0  or mod($P{Year},400)=0  limit 28)
UNION ALL
(select distinct day_n from the_days,the_years,the_months where $P{Month}='Feb' and mod($P{Year},4)=0 and mod($P{Year},100)!=0 or mod($P{Year},400)=0 limit 29) 
like image 78
Ansul Gupta Avatar answered Sep 18 '22 15:09

Ansul Gupta