是否可以按OR顺序对mysql查询进行排序

时间:2017-03-10 14:23:17

标签: mysql

我想按照where子句的顺序来命令查询结果。

例如,我有这个查询:

SELECT * 
  FROM config_ban_num 
 WHERE 
     ( adresse_seo LIKE '12-rue-de-rivoli%' 
    OR adresse_seo LIKE '13-rue-de-rivoli%' 
    OR adresse_seo LIKE '11-rue-de-rivoli%' ) 
   AND (postcode='75004')

当我打印结果时,我得到了这个:

11-rue-de-rivoli
12-rue-de-rivoli
13-rue-de-rivoli

我想关于where子句中的顺序的这个顺序:

12-rue-de-rivoli
13-rue-de-rivoli
11-rue de rivoli

2 个答案:

答案 0 :(得分:1)

一个选项是使用子查询:

SELECT * FROM (
    SELECT *,
      CASE WHEN adresse_seo LIKE '12-rue-de-rivoli%' THEN 1
           WHEN adresse_seo LIKE '13-rue-de-rivoli%' THEN 2
           WHEN adresse_seo LIKE '11-rue-de-rivoli%' THEN 3
           ELSE 4 END as Position
      FROM config_ban_num 
     WHERE 
         ( adresse_seo LIKE '12-rue-de-rivoli%' 
        OR adresse_seo LIKE '13-rue-de-rivoli%' 
        OR adresse_seo LIKE '11-rue-de-rivoli%' ) 
       AND (postcode='75004')
) SubQuery

ORDER BY Position

答案 1 :(得分:1)

使用MySQL's FIELD function

SELECT * 
FROM config_ban_num 
WHERE adresse_seo in ('12-rue-de-rivoli%', '13-rue-de-rivoli%', '11-rue-de-rivoli%') 
AND (postcode='75004')
ORDER BY FIELD(adresse_seo, '12-rue-de-rivoli%', '13-rue-de-rivoli%', '11-rue-de-rivoli%')