简体   繁体   中英

mysql select query with where condition in a range of records

I want to select only those records from a specific range of 10 records where a condition satisfy. That range can be 0-10 or 20-30 or 35-45 or any range.

select Cid, Company_Name, completed from table1;
+-------+----------------------------------------------------+-----------+
| Cid   | Company_Name                                       | completed |
+-------+----------------------------------------------------+-----------+
| 73855 | company 1                                          |         1 |
| 73894 | company 2                                          |         2 |
| 73906 | company 3                                          |         2 |
| 73909 | company 4                                          |         2 |
| 73921 | company 5                                          |         1 |
| 73924 | company 6                                          |         1 |
| 73936 | company 7                                          |         2 |
| 73939 | company 8                                          |         2 |
| 73955 | company 9                                          |         2 |
| 73994 | company 10                                         |         2 |
| 74003 | company 11                                         |         0 |

Now i want to fetch only those records between row number 10-20 in table which have completed=2 .

I tried something like:

select Cid, Company_Name, completed from table1 t1 where completed=2 in (select Cid, Company_Name, completed from table1 t2 limit 10,10);

But this gives me error:

ERROR 1235 (42000): This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

using the limit like this:

select Cid, Company_Name from table1 t1 where completed=2 limit 10,10;

apply where condition first then apply limit of selected result. I want to apply limit first then apply the where condition.

How about something like this: (It seems to work well on the version I tested, which is mySQL 5.6):

select * from (
select * from table1 limit 10, 10) t1 where t1.completed = 2

In mysql we can limit by adding "Offset" before "where":

select Cid, Company_Name from table1 t1 limit 10 offset 0 where completed=2

UPDATED: Source: http://dev.mysql.com/doc/refman/5.5/en/limit-optimization.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM