MariaDB 函数

MariaDB LOCATE() 函数返回给定字符串中指定子字符串第一次出现的位置。如果在给定字符串中未找到子字符串,则此函数返回 0。

此函数执行不区分大小写搜索。请注意,字符串中的第一个位置以 1 开头。

LOCATE() 函数是 POSITION() 函数。

语法

LOCATE(substring, string, start_position) 

    参数

    substring必填。 指定要在string中搜索的子字符串。
    string必填。 指定要搜索的字符串。
    start_position可选。 指定搜索的起始位置。默认位置为 1。

    返回值

    返回字符串中子字符串第一次出现的位置。

    示例 1:

    下面的示例显示了 LOCATE() 函数的用法。

    SELECT LOCATE('Y', 'Yxjc123.com');
    Result: 1
    
    SELECT LOCATE('123', 'Yxjc123.com');
    Result: 5
    
    SELECT LOCATE('.com', 'Yxjc123.com');
    Result: 8
    
    SELECT LOCATE('j', 'Yxjc123.com');
    Result: 3
    
    SELECT LOCATE('1', 'Yxjc123.com', 5);
    Result: 5
    
    SELECT LOCATE('Z', 'Yxjc123.com');
    Result: 0
    
    SELECT LOCATE('ABC', 'Yxjc123.com');
    Result: 0 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    示例 2:

    考虑一个名为 Employee 的数据库表,其中包含以下记录:

    PhoneNumberEmpIDAddress
    +1-80540980001Brooklyn, New York, USA
    +33-1479961012Grenelle, Paris, France
    +31-2011503193Geuzenveld, Amsterdam, Netherlands
    +86-10997324584Yizhuangzhen, Beijing, China
    +65-672348245Yishun, Singapore
    +81-3577990726Koto City, Tokyo, Japan

    在下面的查询中, LOCATE() 函数用于从 PhoneNumber 列记录中提取国家/地区代码。

    SELECT *, SUBSTR(PhoneNumber, 1, LOCATE('-', PhoneNumber) - 1) AS CountryCode 
    FROM Employee; 
    • 1

    这将产生如下所示的结果:

    PhoneNumberEmpIDAddressCountryCode
    +1-80540980001Brooklyn, New York, USA+1
    +33-1479961012Grenelle, Paris, France+33
    +31-2011503193Geuzenveld, Amsterdam, Netherlands+31
    +86-10997324584Yizhuangzhen, Beijing, China+86
    +65-672348245Yishun, Singapore+65
    +81-3577990726Koto City, Tokyo, Japan+81