-1

I have 3 tables. The story is: I will choose materials. And which meals can be made with these ingredients.

And this is my c# codes.

string sql = "SELECT * FROM tblmealmaterials WHERE ";
        string[] idler = textBox1.Text.Split(',');

        for (int i = 0; i < idler.Length; i++)
        {
            for (int s = 0; s < i; s++)
            {
                sql +="( materialId= "+ idler[s] + " and materialId= " + idler[i] +  " )" ;

                if (s<i)
                    sql += " or ";

            }
        }

        sql += " (";
        for (int i = 0; i < idler.Length; i++)
        {
            sql += " materialId="+ idler[i] ;
            if (i<idler.Length-1)
                sql += " and ";
        }
        sql += " )";                

        richTextBox1.Text = sql;

my tables: enter image description here

my sql generator codes c# enter image description here

Siyual
  • 16,415
  • 8
  • 44
  • 58
tuncgulec
  • 13
  • 6

1 Answers1

0
SELECT b.MealID FROM 
(
SELECT mealid, COUNT(*) as IngredientCount FROM tblmealmaterials WHERE materialid in (1,2,3)
GROUP BY mealid
)
a
INNER JOIN tblmealmaterials b
ON a.mealID = b.mealID 
GROUP BY b.MealID
HAVING COUNT(*) = MAX(a.IngredientCount)

The above query will find meals that use any of the ingredients (with the IN clause), and then verify that the recipe only uses those ingredients (by comparing the COUNTs).

To avoid SQL injection issues (and to simplify writing the IN query), I'd recommend using parameterised queries via an ORM. PetaPoco provides nice IN support.

mjwills
  • 23,389
  • 6
  • 40
  • 63
  • Thank you. But : "Column 'a.IngredientCount' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause." – tuncgulec Jun 28 '17 at 13:21