获取 MySQL 中空格前的所有字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3471199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:50:55  来源:igfitidea点击:

Get all characters before space in MySQL

sqlmysql

提问by l--''''''---------''''''''''''

I would like to get all the characters in a field before a space

我想在空格之前获取字段中的所有字符

For example, if field1is "chara ters"

例如,如果field1"chara ters"

I want it to return "chara"

我想要它回来 "chara"

What would this select statement look like?

这个 select 语句会是什么样的?

回答by Mchl

SELECT LEFT(field1,LOCATE(' ',field1) - 1)

SELECT LEFT(field1,LOCATE(' ',field1) - 1)

Note that if the string in question contains no spaces, this will return an empty string.

请注意,如果有问题的字符串不包含空格,这将返回一个空字符串。

回答by T. Brian Jones

Below is another method that works and may seem a bit simpler to some. It uses the SUBSTRING_INDEX MySQL function. A 1 returns everything before the first space, and a -1 returns everything after the last space.

下面是另一种有效的方法,对某些人来说可能看起来更简单一些。它使用SUBSTRING_INDEX MySQL 函数。1 返回第一个空格之前的所有内容,-1 返回最后一个空格之后的所有内容。

This returns 'chara':

这将返回“字符”:

SELECT SUBSTRING_INDEX( field1, ' ', 1 )

This returns 'ters':

这将返回 'ters':

SELECT SUBSTRING_INDEX( field1, ' ', -1 )

Details

细节

A positive value will look for your specified character from the start of the string, and a negative value will start from the end of the string. The value of the number indicates the quantity of your specified character to look for before returning the remaining piece of the string. If the character you are searching for does not exist, the entire field value will be returned.

正值将从字符串的开头查找您指定的字符,负值将从字符串的末尾开始。数字的值表示在返回字符串的剩余部分之前要查找的指定字符的数量。如果您要搜索的字符不存在,则将返回整个字段值。

In this case, a -2 would return everything to the right of the second to last space, which doesn't exist in this example, so the entire field value will be returned.

在这种情况下, -2 将返回倒数第二个空格右侧的所有内容,这在本示例中不存在,因此将返回整个字段值。

回答by soulmerge

You would need some string operationsfor that. Assuming every field has at least one space character:

为此,您需要一些字符串操作。假设每个字段至少有一个空格字符:

SELECT SUBSTR(field1, 0, LOCATE(' ', field1)) FROM your_table;

Safe approach:

安全方法:

SELECT IF(
    LOCATE(' ', field1),
    SUBSTR(field1, 0, LOCATE(' ', field1)),
    field1
) FROM your_table;