简体   繁体   English

Linq-to-sql连接/在哪里?

[英]Linq-to-sql join/where?

I've the following table structures 我有以下表格结构

Users id 用户ID

Types id isBool 类型id isBool

UsersTypes userid types UsersTypes用户ID类型

I want to select all the UserTypes based on id and isBool. 我想基于id和isBool选择所有UserType。

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? 使用join on语法与where,where与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? 在哪里使用cond1 == var1 && cond2 == var2,带括号和不带括号,有什么区别吗? 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. 我可以看到可以执行子查询或使用组,但不能100%确定是否需要。 An example might be helpful. 一个例子可能会有所帮助。 I'm thinking a subquery may be required in this case. 我在这种情况下可能需要子查询。

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. join和where子句之间有区别,这取决于它们的使用方式。 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). 无论哪种方式,都首选使用联接,因为LINQ-to-SQL会生成内部联接,而不是 哈希 交叉联接(然后基于where子句进行过滤)。

You don't need the parenthesis. 您不需要括号。 You can include them though since they do help readability in some cases. 您可以将它们包括在内,因为它们在某些情况下确实有助于提高可读性。

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; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM