查詢條件的值來自另外一次查詢。
例如 sqlserver sql:
select * from products where categoryid=(select top 1 categoryid from categories where categoryname=’produce’)
這條sql的實現代碼如下:
DbSession.Default.From<Products>()
.Where(Products._.CategoryID
.SubQueryEqual(DbSession.Default.From<Categories>().Where(Categories._.CategoryName == "Produce").Select(Categories._.CategoryID).Top(1)))
.ToList();
對比一下組件生成的sql
Text:
SELECT * FROM [Products]
WHERE [Products].[CategoryID] = ( SELECT TOP 1 [Categories].[CategoryID] FROM [Categories] WHERE [Categories]. [CategoryName] = @174b5c8999e2480594cdc08ab4d8e5bd)
Parameters:
@174b5c8999e2480594cdc08ab4d8e5bd[String] = Produce
子查詢方法對應sql表如下:
方法名稱 sql SubQueryEqual = SubQueryNotEqual <> SubQueryLess < SubQueryLessOrEqual <= SubQueryGreater > SubQueryGreaterOrEqual >= SubQueryIn in SubQueryNotIn not in
再寫一個例子
DbSession.Default.From<Products>()
.Where(Products._.CategoryID
.SubQueryNotIn(DbSession.Default.From<Categories>().Where(Categories._.CategoryName == "Produce").Select(Categories._.CategoryID)))
.ToList();
生成的sql如下
Text:
SELECT * FROM [Products]
WHERE [Products].[CategoryID]
NOT IN ( SELECT [Categories].[CategoryID] FROM [Categories] WHERE [Categories].[CategoryName] = @32365a219b864e5fbeb7959a6071d4c8)
Parameters:
@32365a219b864e5fbeb7959a6071d4c8[String] = Produce
子查詢是不是也變的很簡單的呢了。
下一節將講述聯合查詢。