为什么我不能通过对表执行第二次查询来将第二个结果添加到我的列表框中? SQL

时间:2015-03-18 04:03:51

标签: c# mysql sql

我遇到了这个错误,因为我想通过计算每个来自相同电影名称的所有5个不同的评级整数。第一个查询执行得像无瑕疵,但为什么我不能让第二个查询工作,因为下面说的错误?

错误:{“列'RatingNum2'不属于表格表。”}

   private void EachRating_Click(object sender, EventArgs e)
    {
        string filename, connectionInfo;
        SqlConnection db;

        this.listBox1.Items.Clear();

        filename = "netflix.mdf";

        connectionInfo = String.Format(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=
        |DataDirectory|\{0};Integrated Security=True;", filename);

        string moviename = this.textBox1.Text;
        moviename = moviename.Replace("'", "''");

        string five = "5";
        string four = "4";

        db = new SqlConnection(connectionInfo);
        db.Open();

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = db;

        cmd.CommandText = string.Format(
            @"
                SELECT MovieName, RatingNum1 FROM Movies
                INNER JOIN
                (
                SELECT MovieID, Count(Rating) as RatingNum1 FROM Reviews
                WHERE Rating = 5
                GROUP BY MovieID
                )TEMP
                ON TEMP.MovieID = Movies.MovieID
                WHERE MovieName = '{0}';", moviename);

        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        adapter.Fill(ds);

        DataTable dt = ds.Tables["TABLE"];

        foreach (DataRow row in dt.Rows)
        {
            string msg = string.Format("{0}: {1}",
            five.ToString(),
            row["RatingNum1"].ToString());

            this.listBox1.Items.Add(msg);
        }

        SqlCommand cmd2 = new SqlCommand();
        cmd2.Connection = db;

        cmd2.CommandText = string.Format(
            @"
              SELECT MovieName, RatingNum2 FROM Movies
              INNER JOIN
              (
              SELECT MovieID, Count(Rating) as RatingNum2 FROM Reviews
              WHERE Rating = 4
              GROUP BY MovieID
              )TEMP
              ON TEMP.MovieID = Movies.MovieID
              WHERE MovieName = '{0}'", moviename);

        SqlDataAdapter adapter2 = new SqlDataAdapter(cmd2);
        DataSet ds2 = new DataSet();
        adapter.Fill(ds2);

        DataTable dt2 = ds2.Tables["TABLE"];

        foreach (DataRow row2 in dt2.Rows)
        {
            string msg = string.Format("{0}: {1}",
            four.ToString(),
            row2["RatingNum2"].ToString()); //gets the error

            this.listBox1.Items.Add(msg);
        }

1 个答案:

答案 0 :(得分:1)

您正在使用第一个适配器填充第二个数据集,因此数据表无法找到ColumnNum2列

adapter.Fill(ds2);

应该是

adapter2.Fill(ds2);