Mysql: Order by like?

前端 未结 5 1945
抹茶落季
抹茶落季 2020-11-29 00:35

assume that we are performing search using keywords: keyword1, keyword2, keyword3

there are records in database with column \"name\":

1: John Doe
2: Samue         


        
相关标签:
5条回答
  • 2020-11-29 01:10
     SELECT * 
     from
     (
      SELECT u.*, 1 OrderNum 
      FROM users 
      WHERE (name LIKE "%John%")
      UNION 
      SELECT u.*, 2 OrderNum 
      FROM users 
      WHERE (name LIKE "%Doe%")
      )
      Order by OrderNum
    
    0 讨论(0)
  • 2020-11-29 01:10

    My example will Order all of the John's Alphabetically followed by the Doe's.

    ORDER BY CASE
        WHEN name LIKE "John%Doe" THEN CONCAT('a',name)
        WHEN name LIKE "John%"    THEN CONCAT('b',name)
        WHEN name LIKE "%Doe"     THEN CONCAT('c',name)
        ELSE name  
    END  
    
    0 讨论(0)
  • 2020-11-29 01:16

    To build on RedFilter's answer, you could make the rows that have both keywords to be at the top:

    order by case 
    when (name LIKE "%John%" and name LIKE "%Doe%") then 1 
    when name LIKE "%John%" then 2
    when name LIKE "%Doe%"  then 3
    end
    
    0 讨论(0)
  • 2020-11-29 01:23
    order by case 
        when name LIKE "%John%" then 1 
        when name LIKE "%Doe%"  then 2 
        else 3 
    end
    
    0 讨论(0)
  • 2020-11-29 01:31

    Read up on Boolean Fulltext Searches, with which you can do ordering.

    0 讨论(0)
提交回复
热议问题