[英]Query to select a list of values from a table based on this multiple criteria
我有一个包含2列的表,Ex_Id和Term_Id均为int类型。 我的表格中有一个练习ID的许多术语ID。
Table would look like this:
Ex_Id Term_Id
1 2
1 3
1 4
1 5
2 2
3 2
3 4
等等。获取Ex_Id的列表是主要要求。 我的职能就是这样。
List<int> Get_ExId_List(List<int> lst_TermId)
{
// return a list of Ex_Id <int>
}
也就是说,我将传递术语ID的列表,并且需要获取与某些条件匹配的演习ID的列表。 使用此伪代码可以更好地解释选择的标准: SELECT such Ex_Ids FROM table Exercise_Term WHERE Ex_Id has all the corresponding Term_Ids in the lst_TermId
例如,从上面提供的样本表中,
List<int> Get_ExId_List([2])
{
// return [1,2,3]
}
List<int> Get_ExId_List([2,4])
{
// return [1,3]
}
List<int> Get_ExId_List([2,3,4])
{
// return [1]
}
查询部分是我的困惑。 在这种情况下查询将是什么样的? 我可以管理的休息。 希望问题很清楚。 谢谢..
SELECT Ex_ID
FROM TableName
WHERE Term_ID IN (?, ?, ?) --- (2, 3, 4)
GROUP BY Ex_ID
HAVING COUNT(DISTINCT Term_ID) = 3 --- number of terms in the above list
如果表中的组合(Ex_ID, Term_ID)
是唯一的,则可以将COUNT(DISTINCT Term_ID)
替换为COUNT(*)
这是一个关系划分问题。 “标准”解决方案将使用两个否定词(NOT EXISTS):
SELECT DISTINCT Ex_ID
FROM TableName e
WHERE NOT EXISTS
( SELECT *
FROM TableName t
WHERE t.Term_ID IN (?, ?, ?) --- the list of terms
AND NOT EXISTS
( SELECT *
FROM TableName a
WHERE a.Term_ID = t.Term_ID
AND a.Ex_ID = e.Ex_ID
)
)
或更适合您的情况:
SELECT DISTINCT Ex_ID
FROM TableName e
WHERE NOT EXISTS
( SELECT *
FROM
( SELECT ? AS Term_ID
UNION
SELECT ?
UNION
SELECT ?
) AS t
WHERE NOT EXISTS
( SELECT *
FROM TableName a
WHERE a.Term_ID = t.Term_ID
AND a.Ex_ID = e.Ex_ID
)
)
您可以使用LINQ。 将整个表放入某种IEnumerable中,然后使用LINQ。 这是一个例子:
static IEnumerable<int> Get_ExId_List(ICollection<int> lst_TermId)
{
//this is just for the example - get the real data instead
var data = new[] {
new { Ex_Id = 1, Term_Id = 2},
new { Ex_Id = 1, Term_Id = 3},
new { Ex_Id = 1, Term_Id = 4},
new { Ex_Id = 1, Term_Id = 5},
new { Ex_Id = 2, Term_Id = 2},
new { Ex_Id = 3, Term_Id = 2},
new { Ex_Id = 3, Term_Id = 4},
};
return data
.Where(row => lst_TermId.Contains(row.Term_Id))
.GroupBy(row => row.Ex_Id)
.Where(group => group.Count() == lst_TermId.Count())
.Select(group => group.Key);
}
static void Main(string[] args)
{
HashSet<int> lst_TermId = new HashSet<int>();
lst_TermId.Add(2);
Console.WriteLine();
var result = Get_ExId_List(lst_TermId);
foreach (var exid in result)
Console.WriteLine(exid);
lst_TermId.Add(4);
Console.WriteLine();
result = Get_ExId_List(lst_TermId);
foreach (var exid in result)
Console.WriteLine(exid);
lst_TermId.Add(3);
Console.WriteLine();
result = Get_ExId_List(lst_TermId);
foreach (var exid in result)
Console.WriteLine(exid);
}
请注意,如果lst_TermId是HashSet<int>
,则将获得更好的性能,因为contains方法将是O(1)
而不是O(n)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.