select * from table1 where pkey1 in
(select pkey2 from table2 where column1='abc')
其中pkey1和pkey2都是int列。如何在LINQ中將此T-SQL編寫爲sQL?
select * from table1 where pkey1 in
(select pkey2 from table2 where column1='abc')
其中pkey1和pkey2都是int列。如何在LINQ中將此T-SQL編寫爲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
可以幫助你做:)
不是LINQ的答案,但一個完全有效的LINQ到SQL之一:
var results = ctx.ExecuteQuery<Table1>(@"
select * from table1 where pkey1 in
(select pkey2 from table2 where column1='abc')").ToList();
你不要有將每個查詢的控制權移交給LINQ;事實上,在很多情況下,編寫良好的自定義TSQL查詢可以更加高效,從LINQ到SQL生成的效率更高。 LINQ-to-SQL不是批評(對於大多數簡單的查詢來說,它確實很棒)。
var query = from a in db.table1
join b in db.table2 on a.pkey1 equals b.pkey2
where b.column1 == "abc"
select a;
from t in table1
join u in table2 on t.pkey1 equals u.pkey2
where u.column1 == "abc"
select t;
這裏是另一個可能的查詢:
3210您可能需要調用的結果Distinct()
取決於你想如何使用它。生成的SQL相當於:
SELECT [t1].*
FROM table2 AS [t2], table1 AS [t1]
WHERE ([t2].[column1] = 'abc') AND ([t1].[pkey1] = [t2].[pkey2])
你可能會碰到一些問題,當您嘗試雖然叫`pkey2`掉`x`,因爲`x`是`IQueryable` – diceguyd30 2010-12-23 14:17:48
@ diceguyd30工作正常,使用http://www.linqpad.net/並給它一個試試:) – balexandre 2010-12-23 16:49:40
這正是我所做的!如果子查詢只返回一個值,我想它會起作用,但是在我測試過的數據上,它返回了多個值,而x最終成爲`IQueryable`,甚至不會編譯...但... *運行再試一次*^_^ – diceguyd30 2010-12-23 17:28:36