在AS的情况下由ASC订购

时间:2018-02-22 11:03:42

标签: mysql case case-when

这里的表名为:table

|field1 | field 2
------------------
|def-toto    | agh

|abc-toto    | bij

|def         | agh-toto

|abc         | bij-toto

在搜索'toto'上,我想要结果:

  1. abc-toto bij
  2. def-toto agh
  3. def agh-toto
  4. abc bij-toto
  5. traduction =>按字段1 ASC排序(当字段1像%toto%时)然后ORDER BY字段1 ASC(当字段2像%toto%时)

    所以请求:不工作:

    SELECT * FROM table
    
    WHERE field1 LIKE '%toto%' OR field2 LIKE '%toto%'
    
    ORDER BY
    
    CASE
        WHEN nom_com LIKE '%$termeOk%'  THEN 1 ASC
        WHEN desc_com LIKE '%$termeOk%' THEN 2 ASC
    END
    

2 个答案:

答案 0 :(得分:0)

我们可以通过使用双层排序逻辑来解决这个问题。首先,field1中出现toto的记录将在没有此记录的记录之前排序。然后,在这两个组中的每个组中,将发生另一种排序。正面field1记录按toto排序,负面field2记录按SELECT * FROM yourTable WHERE field1 LIKE '%toto%' OR field2 LIKE '%toto%' ORDER BY CASE WHEN field1 LIKE '%toto%' THEN 1 ELSE 2 END, CASE WHEN field1 LIKE '%toto%' THEN field1 ELSE field2 END; 排序。

from sqlalchemy import create_engine
import pymysql
import pandas as pd

db_connection = 'mysql+pymysql://mysql_user:mysql_password@mysql_host/mysql_db'
conn = create_engine(db_connection)

df = pd.read_sql("SELECT * from abc limit 5", conn)

enter image description here

Demo

答案 1 :(得分:0)

试试这个

SELECT * FROM table

WHERE CONCAT(field1,field2)LIKE'%toto%'

ORDER BY field1,field2