简体   繁体   English

更多 LINQY-ness(子选择)

[英]More LINQY-ness (sub-select)

I need to use LINQ to build a kind of weird query that uses a sub-query.我需要使用 LINQ 来构建一种使用子查询的奇怪查询。

I'm really looking for distinct records.我真的在寻找不同的记录。 Normally, the SQL would look like this:通常,SQL 看起来像这样:

select distinct col1, col2 from foo where col3 = somevalue

However, col2 just happens to be a BLOB, so I can't use distinct .但是, col2 恰好是一个 BLOB,所以我不能使用distinct So, I think that the next best SQL looks like this:所以,我认为下一个最好的 SQL 看起来像这样:


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

I'm not sure what is the best way to "phrase" that second query in LINQ.我不确定在 LINQ 中“表达”第二个查询的最佳方式是什么。 Here's what I have so far, and it works, but I'm not sure whether it's optimal:这是我到目前为止所拥有的,它有效,但我不确定它是否是最佳的:


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};


That gives me what I want, but according to SQL Manager, the resulting query is about 8% more expensive than my hand-crafted SQL sub-query.这给了我想要的东西,但是根据 SQL Manager 的说法,生成的查询比我手工制作的 SQL 子查询贵 8% 左右。 Is there a better way to write that?有没有更好的写法?

Can you try this?你能试试这个吗?

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

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

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