MySQL爆炸字符串并删除最后一部分

时间:2015-12-12 14:49:59

标签: mysql sql

我有像

这样的字符串
some1-some2-som3-123
some1-some2-143
some1-1235

如何移除上一部分-123?从该字符串与sql statment

2 个答案:

答案 0 :(得分:3)

您可以从头到尾使用简单的SUBSTRING -

SELECT col, SUBSTRING(col, 0, LENGTH(col) - INSTR(REVERSE(col), '-')) AS result
FROM tab;

SqlFiddleDemo

输出:

╔═══════════════════════╦══════════════════╗
║         col           ║      result      ║
╠═══════════════════════╬══════════════════╣
║ some1-some2-som3-123  ║ some1-some2-som3 ║
║ some1-some2-143       ║ some1-some2      ║
║ some1-1235            ║ some1            ║
╚═══════════════════════╩══════════════════╝

答案 1 :(得分:1)

DEMO

首先找到' - '

的最后一个索引
SELECT LENGTH("first-middle-last") - LOCATE('-', REVERSE("first-middle-last"));

然后提取左侧部分 -

SELECT LEFT("first-middle-last", LENGTH("first-middle-last") - LOCATE('-', REVERSE("first-middle-last")));