tjones
tjones

Reputation: 367

MYSQL How do I select data from one table only where column values from that table match the column values of another table?

I have two tables. I want to get the UIDs from table 1 where the subject columns from both tables match.

Table 1              

UID   SubjectA           
1     Cows           
2     Chickens       
3     Mice           
4     Rabbits        
5     Cows           

Table 2

Name    SubjectB 
A       Cows
B       Cows
C       Cows
D       Cows
E       Mice

Expected Result*

Fetch UIDs: 1, 3, 5.

I don't quite understand joins and unions. Both seem to combine two tables. What is the right way of doing this?

Upvotes: 2

Views: 3571

Answers (1)

Michael Fredrickson
Michael Fredrickson

Reputation: 37398

There are several ways to do this...

First, I'd suggest using exists:

SELECT
    UID
FROM
    Table1
WHERE EXISTS (
    SELECT 1
    FROM Table2
    WHERE SubjectB = SubjectA
)

Or, you can use a join and distinct:

SELECT DISTINCT
    UID
FROM
    Table1 JOIN
    Table2 ON SubjectB = SubjectA

Lastly, you can use in:

SELECT
    UID
FROM
    Table1
WHERE SubjectA IN (
    SELECT SubjectB
    FROM Table2
)

Upvotes: 4

Related Questions