Roshan Sankhe Roshan Sankhe - 4 months ago 8
MySQL Question

How can i show the result using IN clause?

SELECT * FROM `students` WHERE `id` IN (83,84);


Above query give me the result in asc order according to query but when i am change the order like 83 is replace by 84 and 84 is replace by 83 it again give me asc order result. i want to show the result according to query.

Answer

You can use find_in_set in order by clause:

SELECT 
* 
FROM `students` 
WHERE `id` IN (83,84)
ORDER BY FIND_IN_SET(id,'83,84')

Brief note on FIND_IN_SET:

Description

MySQL FIND_IN_SET() returns the position of a string if it is present (as a substring) within a list of strings. The string list itself is a string contains substrings separated by ‘,’ (comma) character.

This function returns 0 when search string does not exist in the string list and returns NULL if either of the arguments is NULL.

Syntax

FIND_IN_SET (search string, string list)

Arguments

Name            Description
search string   A string which is to be looked for in following list of arguments.
string list     List of strings to be searched if they contain the search string.

Related post

Alternatively you can use FIELD() function to accomplish that