Reputation: 1373
I'm trying to figure out how to retrieve all rows with a ID which have a specific value in the other column.
The database looks like this:
I want to retrieve those rows which have a VAL of 2 and the corresponding ID rows. So in this case this would give me all the ID 1 rows and the ID 3 row:
Upvotes: 1
Views: 75
Reputation: 391
Constructions like where id in (select id from ...)
and where exists (select 1 from ...)
may take very long time, because for every row in test
you are executing subquery. To solve your problem you can join test
with itself and make distinct
like this:
SELECT DISTINCT t1.*
FROM test t1
INNER JOIN test t2 ON t1.id = t2.id
WHERE t2.val = 2
Upvotes: 1
Reputation: 1181
you'll need a subquery (or join or cte or derived table) Subquery is easist to visualise
Select * from Test where ID IN (SELECT ID from Test where VAL = 2)
Upvotes: 3
Reputation: 1269563
One method is exists:
select t.*
from test t
where exists (select 1 from test t2 where t2.id = t.id and t2.val = 2);
Upvotes: 2