A query to the database that brings the data in sequence

Asked

Viewed 50 times

-2

Follow a following code snippet:

SELECT user_id, name, firstname
FROM vrp_user_identities
WHERE user_id IN (27, 2, 1, 365, 142)

Returns me an array only with the data I want, but it comes in ascending form when using the IN instead of first coming the data from ID 27 he first pulls the data from ID 1 and so on.

How could I get around this?

  • 1

    It depends on which SQL engine you are using. In large part you can use ORDER BY user_id=142,user_id=365,user_id=1,... - see working here - in others may use specific functions such as ORDE BY FIND_IN_SET( user_id,'27,2...'), etc. Only, probably, even if you edit the question and some answer comes out, it’s not what you really need, which is what we call XY problem.

1 answer

-2


The order needs to be defined by a ORDER BY. Utilize FIELD together to define the sequence of ids.

See an example based on your specific case: sqlfiddle

SELECT user_id, name, firstname
FROM teste
WHERE user_id IN (2, 27, 1, 365, 142)
ORDER BY FIELD (user_id, 27, 2, 1, 365, 142);

The order of user_id in the WHERE does not influence the final result, the ORDER BY that will do this.

  • 2

    ORDER BY You don’t need "field" just for the following fields. Field can be used in mysql, but the question does not say it is this database, so answer does not seem to solve the problem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.