您如何使用新的Linq-to-NHibernate Provider(3.x)编写这个确切的SQL查询
SELECT Post.Title, COUNT(DISTINCT Comment.UserId)
FROM Post
INNER JOIN Comment ON Post.Id = Comment.PostId
GROUP BY Post.Title
如果你想进行一些测试,这里有一些SQL
DECLARE @Post Table(Id int identity(1,1), Title varchar(200))
DECLARE @Comment Table(Id int identity(1,1), PostId int, Comment varchar(200), UserId int)
DECLARE @PostId int
INSERT INTO @Post(Title)
VALUES ('Test')
SELECT @PostId = SCOPE_IDENTITY()
INSERT INTO @Comment(PostId, Comment, UserId)
VALUES (@PostId, 'Test Comment', 1)
INSERT INTO @Comment(PostId, Comment, UserId)
VALUES (@PostId, 'Test Comment 2', 1)
INSERT INTO @Comment(PostId, Comment, UserId)
VALUES (@PostId, 'Test Comment 3', 2)
INSERT INTO @Post(Title)
VALUES ('Test 2')
SELECT @PostId = SCOPE_IDENTITY()
INSERT INTO @Comment(PostId, Comment, UserId)
VALUES (@PostId, 'Test Comment', 1)
INSERT INTO @Comment(PostId, Comment, UserId)
VALUES (@PostId, 'Test Comment 2', 2)
INSERT INTO @Comment(PostId, Comment, UserId)
VALUES (@PostId, 'Test Comment 3', 3)
SELECT Post.Title, COUNT(DISTINCT Comment.UserId)
FROM @Post Post
INNER JOIN @Comment Comment ON Post.Id = Comment.PostId
GROUP BY Post.Title
答案 0 :(得分:2)
我认为目前不可能执行count(distinct x)
部分。
这是我最接近的:
from comment in session.Query<Comment>()
group comment by comment.Post.Title
into g
select new
{
Title = g.Key,
Count = g.Select(x => x.UserId).Distinct().Count()
};
但它产生与SQL完全相同的SQL:
from comment in session.Query<Comment>()
group comment by comment.Post.Title
into g
select new
{
Title = g.Key,
Count = g.Count()
};
这是:
SELECT Post.Title, COUNT(*)
FROM Comment
LEFT JOIN Post ON Post.Id = Comment.PostId
GROUP BY Post.Title
您应该将问题发布到http://jira.nhforge.org。 Linq提供商正在进行大量的工作,并且很有可能在不久的将来支持这种结构。