Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL join two tables to split email from second table

Tags:

sql

join

split

I have the two following tables. Where the username from table A is the first part of the email address in table B.

How do I join the two tables together by using split? Is there another way to do this?

This is my current query:

    SELECT 
    A.Full_name,
    A.Username,
    B.Email,
    FROM
    A
    LEFT JOIN B
    ON A.Username = B.Email

I would like to use split(B.Email, '@') - however I don't think this syntax is correct.

Table A
--------------------------------
Full_name  | Username          |
--------------------------------
John Doe   | johndoe           |
--------------------------------
Jane Smith | janesmith         |
--------------------------------



Table B
----------------------------------
Full_name  | Email               |
----------------------------------
John Doe   | [email protected]   |
----------------------------------
Jane Smith | [email protected] |
----------------------------------
like image 722
Seldy Lee Avatar asked May 16 '26 22:05

Seldy Lee


2 Answers

You can use like operator like this:

SELECT 
A.Full_name,
A.Username,
B.Email,
FROM
A
LEFT JOIN B
ON B.Email like A.Username+'@%'

In this case, the username will have to match exactly with text only upto the @ character.

For SQL Server:

SELECT 
A.Full_name,
A.Username,
B.Email,
FROM
A
LEFT JOIN B
ON Charindex(A.Username+'@',B.Email) = 1

Charindex(A.Username+'@',B.Email) = 1 because it must match from the starting of the email, not anywhere (as the other answer suggest).

Similarly, for Oracle:

SELECT 
A.Full_name,
A.Username,
B.Email,
FROM
A
LEFT JOIN B
ON INSTR(B.Email, A.Username||'@') = 1
like image 99
Gurwinder Singh Avatar answered May 18 '26 16:05

Gurwinder Singh


To the best of my knowledge, mssql doesn't support a split() function. You can use a combination of left() and charindex() to accomplish your objective.

SELECT 
A.Full_name,
A.Username,
B.Email
FROM
A
LEFT JOIN B
ON A.Username = left(B.Email, charindex(',', B.Email)-1)
like image 38
Gene Stempel Avatar answered May 18 '26 15:05

Gene Stempel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!