简体   繁体   English

使用linq连接使用两个表在两个表上

[英]using linq with join using two where on two tables

I am using Csharp Linq to create the following report 我正在使用Csharp Linq创建以下报告

I have two tables as below 我有两张桌子如下

#Users
nid     pid     name
1       1       name1
2       1       name2

#Transactions
nid     tid     location    dcode 
1       T1      L1          D1
2       T1      L2          D1
2       T2      L1          D1
2       T2      L3          D1

The report contains 该报告包含

a) columns from users table where nid != pid
    b) columns from transactions where tid == T2 and nid = results from a)
    c) the combination can have only one top row  in result 

nid     name        tid     Location
2       name2       T2      L1

the second record will not be present
- 2     name2       T2      L3

I have tried the following, using join 我尝试了以下,使用join

var report = (from u in users where u.nid != u.pid
                      join t in transactions
                      where t.tid == "T2"
                      on u.nid equals t.nid
                      select new 
                      {
                        // the report columns
                      }).Distinct().ToList();

on the second 'where' a Error is displayed 在第二个'where'显示错误

thank you for any assistance 谢谢你的帮助

Swap filtering and joining parts of your query and rename tid into t.tid or other desired filtering clause (in your example resulting table does have transactions with tid == "T1" , but you try to filter with T2 ): 交换过滤并连接部分查询并将tid重命名为t.tid或其他所需的过滤子句(在您的示例中,结果表确实具有tid == "T1"事务,但您尝试使用T2过滤):

var report = (from u in users     
              join t in transactions 
              on u.nid equals t.tid     //<-- this line should precede 
              where t.tid == "T2"       //<-- this one
              && u.nid != u.pid
              select new 
              {
                    // the report columns
              }).Distinct().ToList();

Join parts can't be separated, so you can't write where until you finished join with on clause. 连接部分不能分开,因此where完成与on子句的join之前,您无法写入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM