c# - 我需要在表中查询两个重复列中的值
问题描述
我在 ASP.NET Core 中工作。我在查询具有相同的行时遇到问题User_id
,Definition_id
如果有类似的行,我需要行的 ID。
+----+---------+---------------+
| Id | User-id | Definition-id |
+----+---------+---------------+
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 2 | 2 |
| 4 | 3 | 1 |
| 5 | 4 | 1 |
| 6 | 4 | 1 |
| 7 | 5 | 2 |
| 8 | 6 | 1 |
+----+---------+---------------+
我需要像这样查询表,将 { 5, 6 } 返回给我,因为它们具有相同的用户和定义 ID。
我已经尝试Groupby
了这两个值,但我无法得到IQueryable
orIGrouping
给我特定行的 id。
我想它会像那样工作,但事实并非如此。
var placementsWithDuplicates =
from p in _context.Placements
group p by new { p.User_id, p.Definition_id } into what
select new
{
Id = what.Id,
User = what.User_id,
Defi = what.Definition_id,
};
foreach (var p in placementsWithDuplicates)
{
issues.Add(new IssueModel()
{
Type = "Praxe ID[" + p.Id + "]",
Name = "User id [" + p.User + "], Definition id [" + p.Defi + "]",
Detail = "So user shouldnt have data for more definitons!"
});
};
感谢 Satish Hirpara 的最佳答案,它需要一些更新,所以我发布了最终运行良好的东西:
var B = from p in _context.Placements
group p by new { p.User_id, p.Definition_id } into what
where what.Count() > 1
select new
{
User_id = what.Key.User_id,
Definition_id = what.Key.Definition_id
};
var placementsWithDuplicates = from A in _context.Placements
join b in B on new { A.User_id, A.Definition_id } equals new { b.User_id, b.Definition_id }
select A;
解决方案
请在下面找到 SQL 查询:
SELECT A.*
FROM Placements A
INNER JOIN
(SELECT User_id, Definition_id FROM Placements
GROUP BY User_Id, Definition_id
HAVING COUNT(*) > 1) B
ON A.User_id = B.User_id AND A.Defination_id =
B.Defination_id
您可以创建一个临时表以避免连接子查询。
如果您想要 linq 查询,那么我尝试从上面的查询中创建它,请在下面找到它:
--- sub query
var B = from p in Placements
group p by new { p.User_id, p.Definition_id } into what
where what.count() > 1
select new
{ User_id = what.User_id,
Definition_id =what.Definition_id
};
--- join
Var result = from A in Placements
Join B ON A.User_id = B.User_id
AND A.Defination_id = B.Defination_id
Select A
请试试这个。
推荐阅读
- javascript - 无法读取`bind` ReactJS的属性
- python - 通过代理的 RPyC 连接
- html - 处理 React jsx 文件,我想添加渲染的动态图像
- azure - 无法将 azure cloud-init 部署中的烧瓶应用要求安装到 vmss
- c# - 泛型类型推断 - 泛型类型的泛型
- python - Python mysql存储过程callproc()不起作用
- redirect - 通过更改 url 使用 Puppeteer 重定向 url
- javascript - JQuery - 调整窗口大小时重新计算不正确
- cron - 每天运行但不在窗口上运行的 Cron 表达式
- c++ - 如何迭代行对齐像素的子集