user2923125
user2923125

Reputation: 77

MYSQL IN statement with column values from another table

I want to get specific column values from one table and use those values to get information from another table.

I'll use this example: both table1 and table2 contains rows with a "name" column.

I want to select the values of all the "name" columns from table1 meeting conditions and then select rows from table2 which contain any of the names selected from table1. The basic idea is below.

SELECT `name` FROM table1 WHERE...
SELECT `name` FROM table2 WHERE `name` IN(names from the above query)

Hopefully this is clear, thanks.

Upvotes: 0

Views: 92

Answers (2)

Filipe Silva
Filipe Silva

Reputation: 21657

Apart from the answer from KayKay you can also use EXISTS:

SELECT name FROM table2 t2
WHERE EXISTS( SELECT 1
              FROM table t1
              WHERE t2.name = t1.name)

Upvotes: 0

kgautron
kgautron

Reputation: 8263

Just "inject" your first query in the second :

SELECT name FROM table2 WHERE name IN(SELECT name FROM table1 WHERE...)

Upvotes: 1

Related Questions