MYSQL select a piece of a string and order by that piece

前端 未结 4 1319
生来不讨喜
生来不讨喜 2020-12-03 18:24

I have a field with this kind of info \"web-1/1.,web-2/2.,web-3/3.,web-4/4.,web-5/5.\". Other registers could have different values like \"web-1/4.,web-2/5.,web-3/1.,web-4/

相关标签:
4条回答
  • 2020-12-03 18:37

    I would suggest that you look at the MySQL String Functions and more specifically the SUBSTRING_INDEX function. The reason I suggest this one over SUBSTRING is because the number before or after the slash might be more than a single number which would make the length of the first and/or second parts vary.

    Example:

    SELECT   `info`,
             SUBSTRING_INDEX(`info`, '/', 1) AS `first_part`,
             SUBSTRING_INDEX(`info`, '/', -1) AS `second_part`
    FROM     `table`
    ORDER BY `first_part` ASC,
             `second_part` ASC;
    

    Result:

    Result

    Additional Example

    In this example, I'm using CAST to convert the second part into an unsigned integer just in case it contains additional characters such as symbols or letters. In other words, the second part of "web-4/15." would be "15" and the second part of "web-4/15****" would also be "15".

    SELECT   `info`,
              SUBSTRING_INDEX(`info`, '/', 1) AS `first_part`,
              CAST(SUBSTRING_INDEX(`info`, '/', -1) AS UNSIGNED) `second_part`
    FROM     `table`
    ORDER BY `first_part` ASC,
             `second_part` ASC;
    
    0 讨论(0)
  • 2020-12-03 18:44

    If the strings will always match the pattern you described, we can assume that the first value you want to sort on is index position 5 in the string (5 characters from the left). The second character is index 7. With that in mind, you can do the following, assuming that the string 'web-2/1' is in a field named field:

    SELECT
      `field`
    FROM
      `table`
    ORDER BY
      substr(`field`, 5, 1) ASC,
      substr(`field`, 7, 1) ASC;
    

    The substr() functions take the field as the first option, the index we mentioned above, and an option third parameter which is the count for how many characters to include starting from the second option.

    You can tweak this as necessary if the string is slightly off, the main thing being the second option in the subtr() function.

    0 讨论(0)
  • 2020-12-03 18:50

    I would do this

    SELECT info
    FROM table
    WHERE info LIKE 'web-2%'
    ORDER BY info ASC
    
    0 讨论(0)
  • 2020-12-03 18:57

    Just add: ...ORDER BY SUBSTRING(username, 2) ASC

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