使用多个变量过滤数据库

时间:2014-06-13 12:23:28

标签: c# asp.net database

简单地说,我试图根据用户的多个选择来过滤数据库。选择是使用checkboxlist控件进行的。该表如下所示:

Table

目的是让用户点击一个或多个“Eis”,然后检查数据库(确切地说是“Eisen'表”)以查看哪个' 39; Systeem'拥有所有这些。当我超过一个' Eis'被选中。这是由于我不知道如何正确构建以下查询:

SELECT DISTINCT Systeem 
FROM Eisen 
WHERE Eis = {first value from the checkboxlist} AND Eis = {second value from the checkboxlist}

这当然会查找适合Eis值的各行,它们从不适合任何东西。执行此操作的代码如下:

string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        string query = "SELECT DISTINCT Systeem FROM Eisen";

        string condition = string.Empty;
        foreach (ListItem item in CheckBoxList1.Items)
        {
            condition += item.Selected ? string.Format("Eis = '{0}' AND ", item.Value) : "";
        }
        if (!string.IsNullOrEmpty(condition))
        {
            condition = string.Format(" where ({0})", condition.Substring(0, condition.Length - 5));
        }
        SqlCommand cmd = new SqlCommand(query + condition);
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;

                sda.SelectCommand = cmd;
                using (DataSet ds = new DataSet())
                {
                    sda.Fill(ds);
                    GridView1.DataSource = ds;
                    GridView1.DataBind();
                }
            }
        }

我的问题如下。如何构造查询,以便在“Systeem”中查找常见的问题。列并检查哪些列具有“Eis”中的所需值。列?

2 个答案:

答案 0 :(得分:1)

你走了:

SELECT Systeem, count(*)
FROM dbo.Eisen
WHERE Eis IN (1)
GROUP BY Systeem
HAVING count(*) = 1

SELECT Systeem, count(*)
FROM dbo.Eisen
WHERE Eis IN (1, 2)
GROUP BY Systeem
HAVING count(*) = 2

SELECT Systeem, count(*)
FROM dbo.Eisen
WHERE Eis IN (2, 3)
GROUP BY Systeem
HAVING count(*) = 2

请注意,您在Google桌面上的第三个结果不正确 - 除非我读错了。 Systeem是否必须包含所有选定的项目,或仅包含所选项目?

编辑:根据评论,这是另一种情况:

SELECT Systeem, count(*)
FROM dbo.Eisen
WHERE Eis IN (2, 3)
GROUP BY Systeem
ORDER BY count(*) DESC

答案 1 :(得分:0)

使用GROUP BY而不是DISTINCT构建您的查询,如下所示:

SELECT
    Systeem 
FROM
    Eisen 
WHERE
    Eis = {first value from the checkboxlist} 
    OR Eis = {second value from the checkboxlist}
GROUP BY
    Systeem
HAVING
    COUNT(*) = { number of checked checkboxes }