简体   繁体   中英

Comparing two columns in two different tables

I have two tables A and B where table A has a column X , table B has column Y . These columns contain account number information. I want to check whether the account number information in column AX is present in BY .

Note: Both column X and Y can have duplicates because these are like composite primary keys.

How can I do solve this?

This will give you account information in table A that is also present in table B . The check is done by a correlated subquery that checks for each row in A whether the account information is present in B .

SELECT DISTINCT
    X
FROM
    A
WHERE
    EXISTS (
        SELECT
            *
        FROM
            B
        WHERE
            B.Y=A.X
    );

You can use an INNER JOIN , like this:

 SELECT * 
 FROM table1 a 
 INNER JOIN table2 b 
 ON a.X = b.Y

OR

you can go for IF EXISTS ,like this:

SELECT *
FROM table1 a
WHERE EXISTS(
              SELECT 1
              FROM table2 b
              WHERE a.x=b.Y )

select distinct(X)
from A,B
WHERE AX=BY

This will give you a list of account numbers in A that are not in B:

SELECT X FROM (
    SELECT DISTINCT X FROM A
) A
LEFT JOIN B ON Y = X
WHERE Y IS NULL

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