简体   繁体   中英

MySQL “less than” operator doesn't bring correct results

I am using paginating in PHP and MySQL to view next/previous records. The query as below:

$domain_id = 1;
$user_id = 8;
$limit = 5;
$sql = 
'SELECT users.user, users.id FROM users 
  JOIN users_matched_domain ON
        users.id = users_matched_domain.user_id  AND 
        users_matched_domain.domain_id = '.$domain_id.' AND 
        users.id < "'.$user_id.'" 
  ORDER BY users.id ASC LIMIT '.$limit;

Table users as below:

id       user
==       ===
1         a
2         b
3         c
4         d   
5         e
6         f
7         g
8         h
9         i
10        j
11        k
.         .
.         .

The above query doesn't work well, it brings user IDs starting from the first ID in user_id table. ie rows ids (1 to 5), it should give (3,4,5,6,7) as they are less than the user id 8. While, when I update the above query as below:

users.id > "'.$user_id.'" 

Then the paginating working fine for (next, next, next), I get 1-5, then 6-10, 11-15, etc.

I would greatly appreciate your hints. Thanks for your help.

You need a desc sort to the the five just before what you are looking at:

 . . .
 ORDER BY users.id DESC . . .

In other words, you want the sort to be desc for < and asc for > .

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