SELECT/LOCATE Query Outputting Incorrect Results

时间:2019-01-09 21:57:20

标签: mysql sql

I have a column (kills) with values separated by colons as such: 0;2;0. I wanted to select whatever the middle digit may be, and came up with this query:

SELECT RIGHT(kills, LOCATE(';', kills) - 1)-LEFT(kills, LOCATE(';', kills) - 1) FROM stats WHERE id='135' AND LOCATE(';', kills) > 0;

(I'm aware the where clause is specific, it was for debug purposes. It would realistically be set to a variable which outputs the row id)

It works perfectly fine when the results all have the same decimal place such as 1;2;3 or 10;20;30, but returns wild results when the case is otherwise, such as 1;20;30 or 10;20;3.

1;20;21 outputs 0. -- 10;20;2 outputs -10.

2;20;21 outputs -1. -- 20;20;2 outputs -20.

9;20;21 outputs -8. -- 90;20;2 outputs -90.

I would like to select the middle value of all of these values even if one value doesn't share the same decimal place.

1 个答案:

答案 0 :(得分:1)

If you want the middle number of three, then you want the second number. Use substring_index():

select substring_index(substring_index(kills, ';', 2), ';', -1)
相关问题