sql -分组和连接

本文关键字:连接 -分 sql | 更新日期: 2023-09-27 18:15:05

我有这样的模式:

Products (**ProductId**, OwnerId, Name)
Categories (**CategoryId**, Name)
ProductsInCategories( **ProductId**, CategoryId )

当我想返回类别列表时,Linq很简单:

from c in db.Categories
orderby c.Name
select c;

但是,我想只返回包含具有特定OwnerId的产品的类别集。

如果这是正常的T-SQL,那么我可以很容易地做到:

SELECT ProductsInCategories.CategoryId
FROM ProductsInCategories
INNER JOIN Categories ON ProductsInCategories.CategoryId = ProductsInCategories.CategoryId
INNER JOIN Products   ON ProductsInCategories.ProductId  = Products.ProductId
WHERE Products.OwnerId = 3
GROUP BY ProductsInCategories.CategoryId

(但我注意到这个SQL只返回类别id,而不是类别名称,理想情况下我想返回两者)

然而,当我将其转换为Linq时,它不再工作了:

from pic in db.ProductsInCategories
join p in db.Products   on pic.ProductId  equals p.ProductId
join c in db.Categories on pic.CategoryId equals c.CategoryId
orderby c.Name
where p.OwnerId == ownerId
select c;

LinqPad报告这将返回一个包含大量重复条目的大型结果集(类别名称对于每个类别中的产品映射都是重复的)。

这里的解决方案是什么?

谢谢!

sql -分组和连接

var q =
    from c in db.Categorie
    where (from pic in db.ProductsInCategories
          join p in db.Products on pic.ProductId equals p.ProductId
          where p.OwnerId == ownerId && pic.CategoryId == c.CategoryId
          select pic).Any()
    select c;

请运行此SQL语句。如果你得到正确的结果,我们可以把它转换成Linq 2 sql在一起

SELECT CategoryId, Name
FROM Categories
WHERE CategoryId IN (SELECT CategoryId FROM ProductsInCategories PIC
                     INNER JOIN Products P ON PIC.ProductId = P.ProductId
                     WHERE P.OwnerID = @OwnerID)