选择查询偶数和奇数值计数

时间:2015-09-18 09:41:43

标签: c# ado.net

只有当Image_ID1Image_ID2都不是null时,这些方法才会给出结果。 如果其中一个或两个都为null,则显示错误。 除此之外,它仅返回偶数值计数,跳过奇数值计数。 示例,列Image_ID1=1,3,nullImage_ID2=2,4,6。 它必须显示1,2,3,4,6值,但会显示1,2,3,4值的null值。 我该如何解决这些问题?

private void BindGrid()
    {
        MySqlConnection con = new MySqlConnection(constr);
        MySqlCommand cmd = new MySqlCommand("SELECT * FROM images where Image_ID in (" + String.Join(",", getImage_ID()) + ")", con);
        MySqlDataAdapter da = new MySqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        gvImages.DataSource = dt;
        gvImages.DataBind();
    }
    private List<int> getImage_ID()
    {
        List<int> i = new List<int>();
        MySqlConnection con = new MySqlConnection(constr);
        con.Open();
        string query = "Select Image_ID1, Image_ID2 from register where students_ID='" + getStudents_ID() + "'AND Image_ID1 IS NOT NULL AND Image_ID2 IS NOT NULL"; 
        MySqlCommand cmd = new MySqlCommand(query);
        cmd.Connection = con;
        MySqlDataReader reader = cmd.ExecuteReader();
        foreach (DbDataRecord s in reader)
            {
                i.Add(s.GetInt32(0));
                i.Add(s.GetInt32(1));
            }
        return i;
    }

3 个答案:

答案 0 :(得分:0)

我建议使用单个查询/方法:

string sql = @"
    SELECT img.* FROM
    (
        SELECT i.* FROM Images i
        INNER JOIN  register r
          ON i.Image_ID = r.Image_ID1
        WHERE r.students_ID = @studentsID

        UNION ALL

        SELECT i.* FROM Images i
        INNER JOIN  register r
          ON i.Image_ID = r.Image_ID2
        WHERE r.students_ID = @studentsID
    ) img
";

MySqlCommand cmd = new MySqlCommand(sql , con);
cmd.Parameters.Add("@studentsID", MySqlDbType.Int32).Value = getStudents_ID();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);

答案 1 :(得分:0)

而不是在getImage_ID()方法中的foreachloop尝试下面提到的代码

while (reader.Read()) 
{
if (!reader.IsDBNull(reader.GetOrdinal("Image_ID1")))
 i.Add(reader.GetInt32(reader.GetOrdinal("Image_ID1")));

if (!reader.IsDBNull(reader.GetOrdinal("Image_ID2")))
 i.Add(reader.GetInt32(reader.GetOrdinal("Image_ID2")));

}

答案 2 :(得分:0)

问题是你的SQL中的这个条件

"'AND Image_ID1 IS NOT NULL AND Image_ID2 IS NOT NULL"

应该是

"'AND (Image_ID1 IS NOT NULL OR Image_ID2 IS NOT NULL)"

然后foreach正文

if (!s.IsDBNull(0)) i.Add(s.GetInt32(0));
if (!s.IsDBNull(1)) i.Add(s.GetInt32(1));