我的记录集有一个包含这些值的字段:
Product Tree 1->Product Tree 2->Product Tree 3->Product Tree 4
Product Tree 1->Product Tree 2->Product Tree 3
Product Tree 1->Product Tree 2->
我想使用“->”作为分隔符返回倒数第二个分隔值。 所以在我的示例中,第一行将返回“产品树 3”,第二行将返回“产品树 2”,第三行将返回产品树 1。我不能为此目的使用 PHP,它必须在 MYSQL 中完成。
我开始尝试使用 SUBSTRING_INDEX。 我发现:
SELECT REPLACE( SUBSTRING_INDEX( 'Product Tree 1->Product Tree 2->Product Tree 3->Product Tree 4', '->', 3 ) , 'Product Tree 1->', '' ) AS header
返回“产品树 2->产品树 3”,因此在第一个“产品树 1”之后给我下一个分隔的 2 个值。
但是我将如何获得倒数第二个分隔值?
最佳答案
为关系数据库保存数据的一种奇怪格式。假设你可以只使用 string functions并这样做:
SET @foo = 'Product Tree 1->Product Tree 2->Product Tree 3->Product Tree 4';
SELECT substring_index(substring_index(@foo, '->', -2), '->', 1);
关于MYSQL 查询 - 获取倒数第二个分隔值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19821729/