Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
按SQL按字符串排序_Sql - Fatal编程技术网

按SQL按字符串排序

按SQL按字符串排序,sql,Sql,在SQL中,是否可以按字符串而不是按如下升序/降序对查询排序 Select * From people ORDER BY names (john, steve, bob, bill) 在标准SQL中,需要一个case语句 Select * From people ORDER BY (case when names = 'john' then 1 when names = 'steve' then 2 when names = 'bob

在SQL中,是否可以按字符串而不是按如下升序/降序对查询排序

Select * From people ORDER BY names (john, steve, bob, bill)

在标准SQL中,需要一个
case
语句

Select *
From people
ORDER BY (case when names = 'john' then 1
               when names = 'steve' then 2
               when names = 'bob' then 3
               when names = 'bill' then 4
          else 5
         );
有些SQL引擎有实现这一点的快捷方式,但您没有提到您正在使用哪个数据库

例如,在MySQL中,您可以执行以下操作:

order by field(names, 'john', 'steve', 'bob', 'bill');

另一种方法是使用charIndex,即

ORDER BY CharIndex('|'+names+'|','|john|steve|bob|bill|')

Charindex将返回找到的名称的位置,在大列表中找到的越早,Charindex返回的数字越低

@user3208629。是的,如果有两个人被称为约翰,这就行了。两者都将首先出现在列表中。