如何使用LINQ获取相关记录

时间:2010-09-25 21:03:20

标签: sql linq-to-sql

你好我有这个表结构:

**ProductsTable**
ProductID
ProductName

**CategoriesTable**
CategoryID
CategoryName

**ProductCategories**
ProductID
CategoryID

每个产品可以属于多个类别。现在我需要一种方法来查找相关产品。但我想以这种方式:

假设Product1属于笔记本电脑,配件。因此,只能检索属于这两个类别(不只是一个)的那些产品。

SQL查询将起作用,但是如果你能给出LINQ,那将是最好的。

先谢谢

Marc V。

1 个答案:

答案 0 :(得分:1)

<强>更新

这是我的sql解决方案,其中包含setup:

declare @p table(id int, name varchar(10))
declare @c table(id int, name varchar(10))
declare @pc table(pid int, cid int)

insert into @p (id, name) values (1, 'laptop')
insert into @p (id, name) values (2, 'desktop')
insert into @p (id, name) values (3, 'milk')

insert into @c (id, name) values (1, 'computer')
insert into @c (id, name) values (2, 'device')
insert into @c (id, name) values (3, 'food')

insert into @pc (pid, cid) values (1, 1)
insert into @pc (pid, cid) values (1, 2)
--insert into @pc (pid, cid) values (1, 3)
insert into @pc (pid, cid) values (2, 1)
insert into @pc (pid, cid) values (2, 2)
insert into @pc (pid, cid) values (3, 3)


declare @productId int;
set @productId = 1;

select * 
from @p p 
where  
--count of categories that current product shares with the source product 
--should be equal to the number of categories the source product belongs to
(
select count(*) 
from @pc pc 
where pc.pid = p.id
and pc.cid in (
      select cid from @pc pc
      where pc.pid = @productId
  )
) = (select count(*) from @pc pc where pc.pid = @productId)
and
p.id <> @productId
相关问题