【问题标题】:Make a new table with the other tables用其他表创建一个新表
【发布时间】:2017-06-02 13:42:30
【问题描述】:

当我查询时

SELECT a.ID, 
       a.Employee, 
       b.Name, 
       b.[Open Date] 
  FROM tblEmployees a, 
       Stores b

效果很好,但是当我进行查询时

SELECT a.ID, 
       a.Employee, 
       b.Name, 
       b.[Open Date], 
       c.Task 
  FROM tblEmployees a, 
       Stores b, 
       tblTasks c

它不起作用。

sda.Fill(dt) 一直报错:

System.OutOfMemoryException: 'System.OutOfMemoryException'

private DataTable GetData() 
{
    string connString = @"Data Source=aa.database.windows.net;Initial Catalog=aa;Persist Security Info=True;User ID=aa;Password=aa";
    string query = "SELECT a.ID, a.Employee, b.Name, b.[Open Date], c.Task FROM tblEmployees a, Stores b, tblTasks c";
    using (SqlConnection con = new SqlConnection(connString))
    {
        using (SqlCommand comm = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                comm.Connection = con;
                sda.SelectCommand = comm;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }
}

【问题讨论】:

  • 查询返回多少条记录?
  • 您使用旧式连接语法:FROM tblEmployees, Stores, tblTasks 将返回所有这些表 (CROSS JOIN) 的笛卡尔积,这可能非常庞大——而且根本不是您想要的.阅读INNER JOIN。如果您确实希望以某种方式在一个查询中包含所有表,那么您需要UNION ALL(但您会得到一组奇怪的列),或者只需要三个单独的查询到三个单独的表中。
  • 您的查询是 cartesian join 与(可能)十亿条记录。看来您省略了where 子句

标签: c# sql asp.net database


【解决方案1】:

所有表中的数据都是链接的?如果是这样,您必须需要使用 join 语句显式此链接

SELECT a.ID, 
       a.Employee, 
       b.Name, 
       b.[Open Date], 
       c.Task 
  FROM tblEmployees a
  JOIN Stores b on b.id = a.id_store -- explicit our link here
  JOIN Tasks c on c.id = a.id_task -- explicit our link here

但如果您尝试从 3 个不同的表中请求数据,则最好执行 3 个请求

【讨论】:

    【解决方案2】:

    或者,您可以在 where 子句中进行连接:

    SELECT a.ID, 
           a.Employee, 
           b.Name, 
           b.[Open Date], 
           c.Task 
      FROM tblEmployees a, 
           Stores b, 
           tblTasks c
      where a.id = b.employeeid  -- clearly made up these name
      and  c.taskownerid= a.id
    

    顺便说一句,这个问题的标题似乎与实际请求有很大不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多