MySQL - ORDER BY values within IN()

我希望通过 输入到 IN ()函数中的顺序对以下查询中返回的项目进行排序。

输入:

SELECT id, name FROM mytable WHERE name IN ('B', 'A', 'D', 'E', 'C');

产出:

|   id   |   name  |
^--------^---------^
|   5    |   B     |
|   6    |   B     |
|   1    |   D     |
|   15   |   E     |
|   17   |   E     |
|   9    |   C     |
|   18   |   C     |

Any ideas?

94474 次浏览

您需要在表中指定排序顺序的另一列(数字)。IN 子句不是这样工作的。

B - 1
A - 2
D - 3
E - 4
C - 5

比如说

... ORDER BY (CASE NAME WHEN 'B' THEN 0 WHEN 'A' THEN 1 WHEN ...
SELECT id, name
FROM mytable
WHERE name IN ('B', 'A', 'D', 'E', 'C')
ORDER BY FIELD(name, 'B', 'A', 'D', 'E', 'C')

函数返回第一个字符串在剩余字符串列表中的位置。

但是,如果有一个表示排序顺序的索引列,然后按此列进行排序,则性能会好得多。

另一个选择是: Http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html

select *
from tablename
order by priority='High' DESC, priority='Medium' DESC, priority='Low" DESC;

因此,在您的情况下(未经测试)将是

SELECT id, name
FROM mytable
WHERE name IN ('B', 'A', 'D', 'E', 'C')
ORDER BY name = 'B', name = 'A', name = 'D', name =  'E', name = 'C';

取决于你在做什么,我发现它有点古怪,但总是得到它的工作后,发挥了一点点。

这可能对某些人有帮助(p _ CustomerId 在 SP 中被传递) :

SELECT CompanyAccountId, CompanyName
FROM account
LEFT JOIN customer where CompanyAccountId = customer.AccountId
GROUP BY CompanyAccountId
ORDER BY CASE WHEN CompanyAccountId IN (SELECT AccountId
FROM customer
WHERE customerid= p_CustomerId)
THEN 0
ELSE 1
END, CompanyName;

Description: I want to show the account list. Here i am passing a customer id in sp. Now it will list the account names with accounts linked to that customers are shown at top followed by other accounts in alphabetical order.

好好利用

order by INSTR( ',B,C,D,A,' ,  concat(',' , `field`, ',' ) )

避免像

 INSTR('1,2,3,11' ,`field`)

将以无序结果行结束: 1和11交替