Mustang31
Mustang31

Reputation: 282

LINQ from a sql join

I'm trying to understand how to rewrite a join query in LINQ.

SELECT cs.qid,cs.qk FROM location_table pl
JOIN (SELECT qid,qk FROM q_table WHERE att5 = 'process') cs ON pl.qck = cs.qk
WHERE pl.location = 'there' 

Here is the LINQ I started with but it isn't returning the same results as the above SQL

from pl in location_table
from cs in q_table
where s. att5 == 'process'
&& cs.qk == pl.qck
&& pl. location == 'there'

thanks for your help.

Upvotes: 0

Views: 157

Answers (2)

Guvante
Guvante

Reputation: 19221

Have you tried using an explicit join?

from pl in location_table
join cs in q_table on cs.qk equals pl.qck
where s. att5 == 'process'
&& pl. location == 'there'

Upvotes: 0

Justin Pihony
Justin Pihony

Reputation: 67135

You need to use the join keyword

from pl in location_table
join cs in q_table
    on cs.qk equals pl.qck
where cs.att5 == ‘process’ && pl. location == ‘there’
select new{cs.qid, cs.qk}

If you want to rewrite this as an EXISTS since only output from q_table is needed:

SELECT qid,qk 
FROM q_table AS cs
WHERE EXISTS
    (
        SELECT 1 
        FROM location_table pl
        WHERE pl.qck = cs.qk AND pl.location = 'there'
    )
    AND cs.att5 == 'process'

You would do this:

from cs in q_table
where location_table.All(pl=>pl.qck == cs.qk && pl.location == 'there')
    && cs.att5 == 'process'
select new{cs.qid, cs.qk}

They should all end up with the same results. I will leave the performance check up to you :)

Upvotes: 3

Related Questions