我想将以下SQL语句翻译成linq查询:
select COUNT(*), itemid, globalid, title, preview, previewimage, previewimage_alt, link
from (
select distinct Id, itemid, globalid, title, preview, previewimage, previewimage_alt,
(select top 1 link from LikeCounter where GlobalId=x.GlobalId) as link
from [LikeCounter] x
where PortalId=1 and LanguageId=1
) as t
GROUP BY itemid, globalid, title, preview, previewimage, previewimage_alt, link
ORDER BY COUNT(*) desc
查询位于一个视图上,该视图保存“喜欢”对象的记录。由于对象可以在多个位置发布,并且视图设置为允许对特定位置进行过滤,因此在对记录进行分组之前需要一个不同的内容来查找视图计数(这是“链接”的附加查询的原因“专栏”。
在一个linq语句中是否可以嵌套SELECT语句?
内部查询没问题:
(from x in LikeCounter
where x.PortalId==1 && x.LanguageId==1
select new {x.Id, x.ItemId, x.GlobalId, x.LanguageId, x.Title, x.Preview, x.PreviewImage_alt,
Morelink=(from y in LikeCounter
where y.GlobalId==x.GlobalId
select y.Morelink).FirstOrDefault()
}).Distinct()
但是有没有办法通过对不同记录进行分组来扩展它,这会导致只对数据库进行一次查询?
提前感谢任何输入......
尼娜
编辑:
以下查询几乎返回我想要的内容 - 但会向SQL服务器生成多个查询:
(from y in
((from x in LikeCounter
where x.PortalId==1 && x.LanguageId==1
select new {x.Id, x.ItemId, x.GlobalId, x.LanguageId, x.Title, x.Preview, x.PreviewImage_alt,
Link=(from y in Xparo_LikeCounter
where y.GlobalId==x.GlobalId
select y.Link).FirstOrDefault()
}).Distinct())
group y by y.GlobalId into grp
select new {Data=grp, Count= grp.Count()}).OrderByDescending (x => x.Count)
答案 0 :(得分:0)
我认为以下应该可行,但我无法真正测试它。不知道它需要多少次查询
from subq in (from x in LikeCounter
where x.PortalId==1 && x.LanguageId==1
select new {x.Id, x.ItemId, x.GlobalId, x.LanguageId, x.Title, x.Preview, x.PreviewImage_alt,
Morelink=(from y in LikeCounter
where y.GlobalId==x.GlobalId
select y.Morelink).FirstOrDefault()
}).Distinct()
group subq by new {TheCount = subq.Id.Count(), subq.Id, subq.ItemId, subq.GlobalId, subq.LanguageId, subq.Title, subq.Preview, subq.PreviewImage_alt, subq.Morelink } into grouped
order by grouped.TheCount descending;