speshock
speshock

Reputation: 140

SQL conditional data display based on multiple tables and columns

I am attempting to display several columns of tableX data when the value of a specific column matches that of the corresponding column in tableY.

Imagine we have 2 tables: one named person containing a column named membershipid and the other named taskscontaining a column named memberid. In this case, the condition for display a record would be the following:

membershipid on person = memberid on tasks

Does this require the use of a JOIN clause or can I still use the WHERE keyword for this?

Thanks for taking a look.

Upvotes: 2

Views: 956

Answers (3)

Steve Chambers
Steve Chambers

Reputation: 39414

From what I've understood of your question, it sounds like yes you'll need an INNER JOIN to pull out only the rows from tableX where there is a matching value in the joined column in tableY.

So something like:

SELECT tableXcol1, tableXcol2, tableXcol3
FROM tableX
INNER JOIN tableY
ON tableX.specific_column = tableY.specific_column

Upvotes: 2

sayap
sayap

Reputation: 6277

If you only need data from tableX but not from tableY, doing a JOIN would likely give you duplicate data. Use EXISTS instead, e.g.

SELECT person.col1, person.col2
FROM person
WHERE
    EXISTS (
        SELECT 1
        FROM tasks
        WHERE
            person.membershipid = tasks.memberid
    )

Upvotes: 1

Barranka
Barranka

Reputation: 21047

ALthough it can be done with where clauses, I would recommend you to use joins.

The where style (not recommended)

select t1.field1, t1.field2, ...
from aTable as t1, anotherTable as t2
where t1.field1 = t2.field1;

The joinstyle (recommended)

select t1.field1, t1.field2, ...
from aTable as t1 inner join anotherTable as t2 on t1.field1 = t2.field1

Upvotes: 1

Related Questions