Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert to join query

Tags:

sql

join

select t.* from table1 t where t.id NOT IN(
select Id from t2 where usrId in
(select usrId from t3 where sId=value));

I the result i need is like if there are matching id's in t1 and t2 then those id's should be omitted and only the remaining rows should be given to me. I tried converting into join but it is giving me the result i wanted. Below is my join query.

SELECT t.* FROM table1 t JOIN table2 t2 ON t.Id <> t2.Id 
JOIN table3 t3 ON t3.Id=t2.Id WHERE t3.sId= :value

This doesn't feth me the correct result. it was returning all the rows, but i want to restrict the result based on the matching id's in table t1 and table t2. Matching id's should be ommited from the result.I will be passing the value for sId.

like image 211
user3292629 Avatar asked Sep 12 '26 22:09

user3292629


1 Answers

I believe this to be an accurate refactor of your query using joins. I don't know if we can do away with the subquery, but in any case the logic appears to be the same.

select t1.*
from table1 t1
left join
(
    select t2.Id
    from table2 t2
    inner join table3 t3
        on t2.usrId = t3.usrId
    where t3.sId = <value>
) t2
    on t1.Id = t2.Id
where t2.Id is null
like image 142
Tim Biegeleisen Avatar answered Sep 15 '26 10:09

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!