简体   繁体   中英

Oracle SQL select query compare 2 columns

I have a table with these two columns:

USERNAME    EMAIL_ADDRESS
------------------------------
username1   username1@abc.com
username2   username2@abc.com
username3   username3@abc.com

The first column is the username and the second column is <username> with email domain along with it.

How can I compare the two columns using Oracle SQL to find if there are any rows where the email_address column doesn't have the correct corresponding username in the email address format?

find if there are any rows where the email_address column doesn't have the correct corresponding username in the email address format?

Presumably, you want:

select t.*
from mytable t
where t.email_address not like t.username || '%'

This will return all records for which the email_address does not start with username .

You can try and match on the entire user name with an expression like:

where t.email_address not like t.username || '@%'

Given the data you've presented you can use a regular expression to parse out your email address and then compare the USER_NAME to the user name in the email:

WITH cteData(USER_NAME, EMAIL_ADDRESS) AS
       (SELECT 'username1', 'username1@abc.com' FROM DUAL UNION ALL
        SELECT 'username2', 'username2@abc.com' FROM DUAL UNION ALL
        SELECT 'usernameX', 'username3@xyz.com' FROM DUAL UNION ALL
        SELECT 'username4', 'username4@abc.com' FROM DUAL),
     cteEmails AS
       (SELECT um.USER_NAME,
               REGEXP_SUBSTR(um.EMAIL_ADDRESS, '[^@.]+', 1, 1) AS EMAIL_USER_NAME,
               REGEXP_SUBSTR(um.EMAIL_ADDRESS, '[^@.]+', 1, 2) AS EMAIL_COMPANY,
               REGEXP_SUBSTR(um.EMAIL_ADDRESS, '[^@.]+', 1, 3) AS EMAIL_DOMAIN
          FROM cteData um)
SELECT *
  FROM cteEmails
  WHERE USER_NAME <> EMAIL_USER_NAME

which returns

USER_NAME   EMAIL_USER_NAME EMAIL_COMPANY   EMAIL_DOMAIN
usernameX   username3       xyz             com

when run.

db<>fiddle here

You can use Regex

SELECT * FROM your_table where username_col != REGEXP_SUBSTR(email_col, '([^@]+)')

//regex ([^@]+) matches any string before @ character

Example db fiddle example

WITH  da(usr, eml) AS
       (SELECT 'username1', 'username1@abc.com' FROM DUAL UNION ALL
        SELECT 'username2', 'username2@abc.com' FROM DUAL UNION ALL
        SELECT 'username_odd', 'username3@abc.com' FROM DUAL UNION ALL
        SELECT 'username4', 'username4@abc.com' FROM DUAL)
SELECT * FROM da  where usr != REGEXP_SUBSTR(eml, '([^@]+)')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM