Vad Zelenin Vad Zelenin - 2 months ago 6
MySQL Question

Mysql requests. Select from two tables

I've done a little MySQL test and there was a question:


Here's two tables: t1 {t1_id, t1_name}, t2 {t2_id, t1_id, t2_name}.
Provide 3 variants of select request from both tables, for t1.t1_id =
t2.t1_id, and 3 variants of select requests for t1.t1_id != t2.t1_id


And I really stuck there. I only know one way to select through JOINS which I know is the correct one in most cases. Yet it's just 1 variant. Need your help. Thanks

Answer

Other than JOIN you can as well use a Correlated Subquery and WHERE EXISTS with those same condition as in join condition

Using EXISTS

select * from t1
where exists(select 1 from t2 where t1.t1_id = t1_id);

Correlated Subquery

select * from t1
where t1_id in (select t1_id from t2);
Comments