【发布时间】:2010-12-23 10:37:14
【问题描述】:
select * from table1 where pkey1 in
(select pkey2 from table2 where column1='abc')
其中 pkey1 和 pkey2 都是 int 列。
【问题讨论】:
标签: .net linq tsql linq-to-sql
select * from table1 where pkey1 in
(select pkey2 from table2 where column1='abc')
其中 pkey1 和 pkey2 都是 int 列。
【问题讨论】:
标签: .net linq tsql linq-to-sql
类似:
from t1 in table1
let x = from t2 in table2 where t2.column1.Equals("abc") select t2
where t1.pkey1.Equals(x.pkey2)
select t1;
你最终知道let可以帮助你做什么:)
【讨论】:
x 调用pkey2 时可能会遇到一些问题,因为x 是IQueryable
IQueryable 并且甚至不会编译......尽管如此...... 跑去再试一次 ^_^
x 输入为IQueryable,但如果你看到它在你的盒子上运行,那对我来说已经足够了!
不是 LINQ 答案,而是完全有效的 LINQ-to-SQL 答案:
var results = ctx.ExecuteQuery<Table1>(@"
select * from table1 where pkey1 in
(select pkey2 from table2 where column1='abc')").ToList();
您没有必须将每个查询的控制权交给 LINQ;实际上,在许多情况下,编写良好的自定义 TSQL 查询比从 LINQ-to-SQL 生成的查询要高效得多。这不是对 LINQ-to-SQL 的批评(它对于大多数简单的查询等都做得很好)。
【讨论】:
reader.NextResult() 进行迭代是唯一的选择?
ctx.Translate<TResult>(DbDataReader) 让 LINQ 为您进行对象映射。
.ExecuteQuery - 这是一个相当简单的 LINQ 操作,L2SQL 应该可以毫无问题地转换为本机 SQL。但请记住你的观点。
from t in table1
join u in table2 on t.pkey1 equals u.pkey2
where u.column1 == "abc"
select t;
【讨论】:
var query = from a in db.table1
join b in db.table2 on a.pkey1 equals b.pkey2
where b.column1 == "abc"
select a;
【讨论】:
== 而不是 = ... 而且我们不应该总是使用 .Equals 而不是 == 吗?
= 已更新。 w.r.t. .Equals,因为我们正在比较原始值(字符串、字符串),所以我将使用 ==。这里不用担心引用,这是.Equals的主要用途。
"abc",不是'abc'吗?
'' 的提及 - 认为我该睡觉了。 :)
这是另一个可能的查询:
var q = from t2 in table2.Where(x => x.column1 == "abc")
from t in table1.Where(x => x.pkey1 == t2.pkey2)
select t;
您可能需要在结果上调用Distinct(),具体取决于您希望如何使用它。生成的SQL相当于:
SELECT [t1].*
FROM table2 AS [t2], table1 AS [t1]
WHERE ([t2].[column1] = 'abc') AND ([t1].[pkey1] = [t2].[pkey2])
【讨论】: