简体   繁体   English

如何将 SQL 查询按一列的计数和每个连接表的一列连接两列和组变成 LINQ?

[英]How can I turn SQL query that joins two columns and groups by count of one column and a column of each joined table into LINQ?

In my database, each URI has associated tags (Tag table) and each pageview (PageView table) is associated with someone viewing a particular page.在我的数据库中,每个 URI 都有关联的标签(Tag 表),每个页面浏览量(PageView 表)都与查看特定页面的人相关联。 I want to return a list of URIs that have the same tags as a given URI, by count of each URI that shares those tag(s).我想通过共享这些标签的每个 URI 的计数,返回与给定 URI 具有相同标签的 URI 列表。 My SQL query looks like this:我的 SQL 查询如下所示:

select count(URI) as 'Count', p.URI, t.Name
from tracking.PageView as p
inner join  Tracking.Tag as t on p.ID = t.PageViewID
where t.name in 
    (select t.Name
    from tracking.PageView as p
    inner join  Tracking.Tag as t on p.ID = t.PageViewID
    where p.URI = 'URI WE WANT TAGS OF'
    )
and p.uri like '%/articles/%'
group by p.URI , t.name
order by Count desc


My apologies if the description is too vague for the query or if the query itself is rough.如果描述对于查询来说太模糊或者查询本身很粗糙,我深表歉意。 It was just the first one that worked.这只是第一个起作用的。 I've tried to separate the subquery into a variable and select values in that subquery, but it's been some time since I've used LINQ and I'm spinning wheels at this point.我试图将子查询分成一个变量和该子查询中的 select 值,但是自从我使用 LINQ 以来已经有一段时间了,此时我正在旋转轮子。

The following is pretty much an exact translation of your current SQL query, which should get you started.以下几乎是您当前 SQL 查询的准确翻译,应该可以帮助您入门。

from p in tracking.PageView
join t in Tracking.Tag on p.ID equals t.PageViewID
where p.uri.Contains("/articles/")
   && (
       from p2 in tracking.PageView
       join t2 in Tracking.Tag on p2.ID equals t2.PageViewID
       where p2.URI == "URI WE WANT TAGS OF"
       select t2.name
      ).Contains(t.name)
group new { p, t } by new { p.URI, t.name } into g
orderby g.Count() descending
select new {
    Count = g.Count(),
    g.Key.URI,
    g.Key.Name
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM