gpt4 book ai didi

c# - LINQ to SQL 从多对多表中选择完全匹配的记录

转载 作者:太空宇宙 更新时间:2023-11-03 15:33:29 25 4
gpt4 key购买 nike

我需要有关在 SQL 中查找匹配记录的帮助。我的下表缓解了多对多问题,其中 GridToPageID 是主键,并且可以有多个具有不同 PageID 的单个 GridID 实例。

enter image description here

在我的应用程序中,参数将与特定的 PageID 列表一起传递,我需要查询并仅查找与传递的 PageID 的确切数量匹配的记录。当我使用下面的查询查询 SQL 时,它会返回所有具有 2 个或更多匹配项的记录,而我只想获得一个恰好具有这 2 个匹配项的记录。

SELECT [GridID]
FROM [AgencySalesAgreementU01].[dbo].[GridToPage]
where PageID in('11aida','30aida') --or any number
group by gridid
having COUNT (GridToPageID) = 2 --match the number of PageID's passed

这是在 LinqPad 中测试的同一个 linq-to-sql 查询

string[] allpages ={"11aida","30aida"};//,"32aida"};

var result = from gtp in GridToPage
where allpages.Contains(gtp.PageID)
group gtp by gtp.GridID into grp
where grp.Count() == allpages.Count()
select grp.Key;
result.Dump();

上述查询的结果返回 GridID 261、263 和 266,而我希望它只返回 261。如果我传递三个 PageID,我需要它返回 263 和 266。同样,对于 PageID '11aida',它会返回 268。

最佳答案

您应该首先将数字分组,然后在组内确定所有 PageID 是否都在 allpages 列表中:

string[] allpages ={"11aida","30aida"};//,"32aida"};
var count = allpages.Count();

var result = from gtp in GridToPage
group gtp by gtp.GridID into grp
where grp.Count() == count
&& grp.All(x => allpages.Contains( x.PageID))
select grp.Key;

关于c# - LINQ to SQL 从多对多表中选择完全匹配的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32829144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com