How to select domain name from email address

后端 未结 13 2467
半阙折子戏
半阙折子戏 2020-12-08 02:05

I have email addresses like user1@gmail.com, user2@ymail.com user3@hotmail.com ... etc. I want a Mysql SELECT that will trim user name

相关标签:
13条回答
  • 2020-12-08 02:34

    Using SUBSTRING_INDEX for "splitting" at '@' and '.' does the trick. See documentation at http://dev.mysql.com/doc/refman/5.1/de/string-functions.html#idm47531853671216.

    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(email, '@', -1), '.', 1);
    

    Example:

    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX("foo@bar.buz", '@', -1), '.', 1);
    

    will give you "bar".

    Here is what happens:
    * Split "foo@bar.buz" at '@'. --> ["foo", "bar.buz"]
    * Pick first element from right (index -1). --> "bar.buz"
    * Split "bar.buz" at '.' --> ["bar", "buz"]
    * Pick first element (index 1) --> "bar"
    Result: "bar"

    If you also need to get rid of subdomains, use:

    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(email, '@', -1), '.', -2), '.', 1);
    

    Example:

    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX("foo@1.2.3.bar.buz", '@', -1), '.', -2), '.', 1);
    

    will give you "bar".

    0 讨论(0)
  • 2020-12-08 02:34

    If you want to know the most used domain names from email addresses you have (can be usefull), you can do :

    select (SUBSTRING_INDEX(SUBSTR(email, INSTR(email, '@') + 1),'.',1)) as a,count(*) as c
    FROM User
    group by a
    order by c desc;
    

    Result :

    0 讨论(0)
  • 2020-12-08 02:39

    Assuming that the domain is a single word domain like gmail.com, yahoo.com, use

    select (SUBSTRING_INDEX(SUBSTR(email, INSTR(email, '@') + 1),'.',1))
    

    The inner SUBSTR gets the right part of the email address after @ and the outer SUBSTRING_INDEX will cut off the result at the first period.

    otherwise if domain is expected to contain multiple words like mail.yahoo.com, etc, use:

    select (SUBSTR(email, INSTR(email, '@') + 1, LENGTH(email) - (INSTR(email, '@') + 1) - LENGTH(SUBSTRING_INDEX(email,'.',-1)))) 
    

    LENGTH(email) - (INSTR(email, '@') + 1) - LENGTH(SUBSTRING_INDEX(email,'.',-1)) will get the length of the domain minus the TLD (.com, .biz etc. part) by using SUBSTRING_INDEX with a negative count which will calculate from right to left.

    0 讨论(0)
  • 2020-12-08 02:40

    Try this:

    select SUBSTR(field_name, INSTR(field_name, '@'), INSTR(field_name, '.'))
    
    0 讨论(0)
  • 2020-12-08 02:41

    I prefer:

    select right(email_address, length(email_address)-INSTR(email_address, '@')) ...
    

    so you don't have to guess how many sub-domains your user's email domain has.

    0 讨论(0)
  • 2020-12-08 02:47
    SELECT SUBSTR(NAME,INSTR(NAME,'@')+1) FROM ORACLE;
    

    Oracle is my table.Don't be confuse.

    0 讨论(0)
提交回复
热议问题