views:

77

answers:

2

I've the following table structures

Users id

Types id isBool

UsersTypes userid types

I want to select all the UserTypes based on id and isBool.

I tried this query

var q = from usertype in usertypes
        from type in types
        where type.isBool == false
        where userstypes.user == id
        select usertype;

But this did not work as expected. My questions are:

  1. Why?
  2. Is there any difference in using the join on syntax vs where, where vs where cond1 && cond2? My understanding is query optimizer will optimize.
  3. Is there any difference in using where cond1 == var1 && cond2 == var2 with and without the parenthesis? This seems peculiar that it is possible to build this without parenthesis
  4. What type of query do I need in this case? I can see that I could do a subquery or use a group but not 100% sure if it is required. An example might be helpful. I'm thinking a subquery may be required in this case.
+2  A: 

Your query doesn't join those two tables on any common field:

var q = from u in usertypes
        join t in types on u.typeid equals t.id
        where t.isBool == false && usertypes.user == id
        select u;

There are differences between join and where clauses, depending on how they're used. Either way, using a join is preferred because LINQ-to-SQL will generate an inner join rather than a hash cross join (and then filtering based on the where clause).

You don't need the parenthesis. You can include them though since they do help readability in some cases.

Justin Niessner
@Justin Thanks works. But is it possible to do this without the explicit join? Can you provide example of using selectmany for this too.
Curtis White
"LINQ-to-SQL will generate an inner join rather than a hash join" Huh? False. Linq to sql doesn't generate hash joins... it generates sql. Query optimizer generates hash joins based on statistics without your input.
David B
@David B - Sorry...bad terminology. How about cross join? The equivalent to `select u.* from usertype as u, type as t`
Justin Niessner
That's correct, but not really relevent. Regardless of the INNER JOIN or filtered CROSS JOIN in the sql text, the query optimizer will know what's up and generate the same plan. If it doesn't change the query plan, why should we care about the generated text?
David B
+1  A: 
var q = from usertype in usertypes 
        from type in types
        where type.isBool == false 
        where usertype.user == id 
        where usertype.typeid = type.id //join criteria
        select usertype; 
David B
@David Thanks. I see forgot the join criteria.
Curtis White
Np. That's the major reason "join" is preferred: it's impossible to forget the join criteria when authoring and it's easy to identify the join criteria vs filtering criteria when reading.
David B