Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

php

mysql

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/2.,web-5/3."

I want to select and order by lets say web-2/? would be web-2/1, web-2/2, web-2/3 and so on all fields that contain web-2 and order by the last number

I want to create a featured properties script different websites and specify feature number. Different properties, different websites different order

like image 958
charlymz Avatar asked Jun 25 '11 04:06

charlymz


People also ask

How do I select a part of a string in MySQL?

MySQL SUBSTRING() Function The SUBSTRING() function extracts a substring from a string (starting at any position). Note: The SUBSTR() and MID() functions equals to the SUBSTRING() function.

What is Find_in_set in MySQL?

The FIND_IN_SET() function returns the position of a string within a list of strings.

How do I remove a specific character from a string in MySQL?

Remove characters from string using TRIM() TRIM() function is used to remove any character/ whitespace from the start/ end or both from a string.


1 Answers

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;
like image 71
Francois Deschenes Avatar answered Sep 26 '22 18:09

Francois Deschenes