更多LINQY ness(子选择)

本文关键字:选择 LINQY ness 更多 | 更新日期: 2023-09-27 17:58:01

我需要使用LINQ来构建一种使用子查询的奇怪查询。

我真的在寻找与众不同的唱片。通常,SQL看起来是这样的:

select distinct col1, col2 from foo where col3 = somevalue

然而,col2恰好是一个BLOB,所以我不能使用distinct。所以,我认为下一个最好的SQL是这样的:


select f1.col1, f1.col2 
from foo f1 where f1.id in 
  (select distinct f2.id from foo f2 where f2.col3 = somevalue

我不确定在LINQ中"表达"第二个查询的最佳方式是什么。以下是我目前所拥有的,它是有效的,但我不确定它是否是最佳的:


var query = from f in foo
            where f.col3 == somevalue
            select new {id = f.id};
var result = from f in foo
             join q in query on f.id equals q.id
             select new MyType() {col1 = f.col1, col2 = f.col2};

这就满足了我的需求,但根据SQL Manager的说法,生成的查询比我手工制作的SQL子查询贵大约8%。有更好的写法吗?

更多LINQY ness(子选择)

你能试试这个吗?

var result = from f in foo
             where query.Contains(f.id)
             select new MyType() {col1 = f.col1, col2 = f.col2};