繁体   English   中英

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

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

我有以下表格结构

用户ID

类型id isBool

UsersTypes用户ID类型

我想基于id和isBool选择所有UserType。

我试过这个查询

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

但这没有按预期工作。 我的问题是:

  1. 为什么?
  2. 使用join on语法与where,where与where cond1 && cond2有什么区别? 我的理解是查询优化器会优化。
  3. 在哪里使用cond1 == var1 && cond2 == var2,带括号和不带括号,有什么区别吗? 这似乎很奇怪,可以在不带括号的情况下构建它
  4. 在这种情况下,我需要哪种查询? 我可以看到可以执行子查询或使用组,但不能100%确定是否需要。 一个例子可能会有所帮助。 我在这种情况下可能需要子查询。

您的查询不会在任何公共字段上合并这两个表:

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;

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

您不需要括号。 您可以将它们包括在内,因为它们在某些情况下确实有助于提高可读性。

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