How to get a specific string always in mysql query using Limit

I have a sql query to get the first 40 users. I want one user to always be on this list. Any of them in the request defining a user identifier with a limit

+4
source share
5 answers

The best way I can think of is:

SELECT * FROM tbl WHERE userid='your-user-id' UNION SELECT * FROM tbl WHERE userid!='your-user-id' LIMIT 39 

Basically, you select your user, and then choose 39 others. You use UNION to combine two SELECT results.

+5
source
 SELECT * FROM `users` WHERE `user_id` != 12345 LIMIT 39 UNION SELECT * FROM `users` WHERE `user_id` = 12345 ORDER BY `user_id` ; 

This will give you the first 39 users + users with user_id = 12345.

+1
source

I guess it will be

 (SELECT * from users limit 39) UNION ALL (SELECT * from users where userid='your-user-id') 
0
source
 Select * from table order by userd_id limit 40 
0
source

Since most of the options are already provided, check if this can help you.

 select name from user_details where id = user_id || id != user_id order by field (id,user_id) desc limit 40; 

This will give you the combination results, and if you want your specified user ID to always be at the top.

0
source

All Articles