简体   繁体   中英

Select all characters in a string until a specific character MySQL

I have a record in an SQL database that looks like this:

'839af0d3-9301-33d0-abce-e16a673980fd', 'Aforic', '7:74324:35:4:1:1203:348:27:415:158:2:0:0:0D-5H-17M-26S', 'Tactician', ' '

The table is defined as follows:

`T1` (`player_uuid`, `player_name`, `stats`, `inventory`, `selected`) 

How do I write a query to select only the name and the first entry from "stats". Basically, I only want to select the first entry in "stats" that is before ":". In this case, it would be 7.

Thank you!

Use SUBSTRING_INDEX .

select player_name,substring_index(stats,':',1) 
from T1

Edit: Splitting the values between the first 3 : delimiters,

select player_name
,substring_index(stats,':',1) as col_1
,substring_index(substring_index(substring_index(stats,':',3),':',-2),':',1) as col_2
,substring_index(substring_index(stats,':',3),':',-1) as col_3
from T1

The alternative solution using LEFT and LOCATE functions:

SELECT
    player_name, LEFT(stats, LOCATE(':', stats) - 1)
FROM 
    T1

Note:

For functions that operate on string positions, the first position is numbered 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM