查询条件的值来自另外一次查询。

例如  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

子查询是不是也变的很简单的呢了。

 

下一节将讲述联合查询。

posted on 2010-01-27 09:01  steven hu  阅读(5304)  评论(9编辑  收藏  举报