About SelectWhereIn sorting

Source: Internet
Author: User
Many people do not know how to sort fields by SelectWhereIn in SQL. If the SQL statement is:

Many people do not know how to sort fields by the content of Select Where In SQL. If the SQL statement is:


The Code is as follows:
Select *
FROM table1
Where (id in (, 2 ))

The Code is as follows:
Select *
FROM table1
Where (id in (, 2) if all the conditions after In are numbers, the MSSQL sorting should be


The Code is as follows:
Select *
FROM table1
Where (id in (, 2 ))
OrDER by charindex (',' + CONVERT (nvarchar, ID) + ',' + CONVERT (nvarchar, Replace ('3, 5, 1, 4, 2 ','', '') + ',')

The Code is as follows:
Select *
FROM table1
Where (id in (, 2 ))
OrDER by charindex (',' + CONVERT (nvarchar, ID) + ',' + CONVERT (nvarchar, Replace ('3, 5, 1, 4, 2 ','', '') + ',') improve the method. Instead of processing spaces, use spaces to judge. it can be used to determine a few character conditions with spaces.

The Code is as follows:
Select *
FROM table1
Where (id in (, 2 ))
OrDER by patindex ('%' + CONVERT (nvarchar (4000), ID) + '%', ''+ CONVERT (nvarchar (4000), Replace ('3, 5, 1, 4, 2 ',') + '')

The Code is as follows:
Select *
FROM table1
Where (id in (, 2 ))
OrDER by patindex ('%' + CONVERT (nvarchar (4000), ID) + '%', ''+ CONVERT (nvarchar (4000), Replace ('3, 5, 1, 4, 2 ',') + '')

In fact, it is better to query and sort conditional strings after processing them out of SQL.
For MYSQL sorting, it may be changed to (not familiar with MYSQL ):

The Code is as follows:
Select *
FROM table1
Where (id in (, 2 ))
OrDER BY FIND_IN_SET (ID, '3, 5, 1, 4, 2 ')

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.