如何处理LEFT JOIN查询中的选定数据?

时间:2018-05-15 08:30:34

标签: c# sql .net sql-server database

我想执行一个选择所有客户的查询,以及每个客户的相应地址。每个客户都可以拥有零个,一个或多个地址。

这是我尝试过的:

sql = "SELECT customers.*, addresses.* FROM customers LEFT JOIN addresses ON addresses.CustomerId = customers.Id ORDER BY customers.Id OFFSET @start ROWS FETCH NEXT @end ROWS ONLY";

List<SqlParameter> parameters = new List<SqlParameter>();
parameters.Add(new SqlParameter("@start", limitStart));
parameters.Add(new SqlParameter("@end", limitEnd));
DataSet set = Db.ExecuteSelectQuery(sql, parameters);


DataTable table = set.Tables["customers"];

Console.WriteLine("Tables count: " + set.Tables.Count); // says there's 1 table.

List<Customer> customers = new List<Customer>();

foreach(DataRow row in table.Rows)
{
    Customer cust = new Customer();
    cust.Id = row.Field<int>("Id");
    cust.ClientNumber = row.Field<string>("clientnumber");
    cust.Date = DateTime.Parse(row.Field<string>("date"));
    cust.Firstname = row.Field<string>("firstname");
    cust.Insertion = row.Field<string>("insertion");
    cust.Lastname = row.Field<string>("lastname");

    foreach(DataRow addrRow in /* ......?...... */) // Want to loop through addresses of the current customer row.
    {
        Address address = new Address();
        address.Street = addrRow.Field<string>("Street");
        address.HouseNumber = addrRow.Field<string>("Number");
        address.PostalCode = addrRow.Field<string>("PostalCode");
        address.City = addrRow.Field<string>("City");
        address.Country = 0;// row.Field<int>("CountryCode");

        cust.Addresses.Add(address);
    }

    customers.Add(cust);
}

return customers;

问题在于我不知道如何使用DataTable的{​​{1}}和DataSet类来处理查询结果。

我在互联网上找不到任何解释您可以访问每个客户所选地址的方式。

有人可以解释一下,或者可能给我看一个代码示例吗?

2 个答案:

答案 0 :(得分:0)

您应该过滤属于客户的地址,该客户是循环中的当前客户

您甚至可以使用if子句将cust.Idrow.Field<int>("CustomerId")进行比较

答案 1 :(得分:0)

您可能希望在第二个

中使用linq库
 foreach(DataRow addrRow in /* ......?...... */) // Want to loop through addresses of the current customer row.
{

像这样:

foreach(DataRow addrRow in table.Rows.Where(x=>x.Field<int>("Id")==cust.Id)) // Want to loop through addresses of the current customer row.
{

您的代码仍会在客户列表中生成重复的客户条目,因此可能会在第一个foreach循环的顶部添加条件:

foreach(DataRow row in table.Rows)
{
  if(customers.Where(x=>x.Id == row.Field<int>("Id").Any())continue;