SQL: ORDER BY two columns intermixed, not priority based

前端 未结 4 1370
一整个雨季
一整个雨季 2021-01-13 11:13

I\'m using mySQL. I have to order names of Contacts by Lastname but in the case that there is no last name, I order by firstname.

This looks like:

OR         


        
相关标签:
4条回答
  • 2021-01-13 11:45
    ORDER BY
    CASE  
      WHEN LName is null
      THEN FName 
      ELSE LName
      END 
    

    more here

    0 讨论(0)
  • 2021-01-13 11:47

    Try using Coalesce
    Note: this would require you not to store empty last names using an empty string (ie "")

    ORDER BY Coalesce(LastName, FirstName)
    

    As Suggested in the Comments By adding FirstName to the order By list again you will properly order two people with the same lastName. Here is an example.

    ORDER BY Coalesce(LastName, FirstName), FirstName
    
    0 讨论(0)
  • 2021-01-13 11:48

    ORDER BY supports custom sorting. But given your logic, I would suggest creating a field in your SELECT with CONCAT and then ordering on it.

    SELECT *, IF(LENGTH(lastname) = 0, firstname, CONCAT(lastname, ', ', firstname)) AS fullname
    FROM contacts
    ORDER BY fullname;
    

    This also has the benefit of returning fullname in your results based on your same sorting logic.

    0 讨论(0)
  • 2021-01-13 11:55

    Use COALESCE and NULLIF:

    ORDER BY COALESCE(NULLIF(LastName, ''), FirstName), FirstName
    
    0 讨论(0)
提交回复
热议问题