我有一个包含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>
}
也就是说,我将传递一个Term ID列表,我需要获得一个符合某些标准的Exercise Ids列表。使用此伪代码可以更好地解释选择标准: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]
}
查询部分是我的困惑。在这种情况下查询会是什么样的?休息,我可以管理。希望问题很清楚。感谢..
答案 0 :(得分:2)
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
)
)
答案 1 :(得分:1)
您可以使用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)
。