Tutorials for drop down menu search in PHP

后端 未结 1 2013
迷失自我
迷失自我 2021-01-29 06:33

I\'m really new to PHP still and I have learnt a little from the community but I still have a lot to learn and I was hoping you guys could give me advice on this question.

相关标签:
1条回答
  • 2021-01-29 06:39

    Here's how I'd do it. Schema first:

    CREATE TABLE ingredients (
      id INT NOT NULL AUTO_INCREMENT,
      name VARCHAR(40) NOT NULL,
      PRIMARY KEY (`id`)
    );
    
    CREATE TABLE recipe (
      id INT NOT NULL AUTO_INCREMENT,
      name VARCHAR(40) NOT NULL,
      PRIMARY KEY (`id`)
    );
    
    CREATE TABLE recipe_ingredients (
      recipe_id INTEGER,
      ingredient_id INTEGER
    );
    

    Now for a query. All recipes that contain a numbered ingredient:

    SELECT
      recipe.name
    FROM
      recipe
      INNER JOIN recipe_ingredients ri ON (recipe.id = ri.recipe_id)
    WHERE
      ri.ingredient_id = 1;
    

    All recipes that contain at least one of several ingredients:

    SELECT DISTINCT
      recipe.name
    FROM
      recipe
      INNER JOIN recipe_ingredients ri ON (recipe.id = ri.recipe_id)
    WHERE
      ri.ingredient_id IN (1, 2, 5);
    

    Or, if you want to search by ingredient name:

    SELECT
      recipe.name
    FROM
      recipe
      INNER JOIN recipe_ingredients ri ON (recipe.id = ri.recipe_id)
      INNER JOIN ingredients i ON (ri.ingredient_id = i.id)
    WHERE
      i.name = 'egg';
    

    The first of these queries is a bit quicker, since there are less joins, and it is faster to search for an integer key than a string. That said, with the volumes of data you are likely dealing with here, it probably won't make much difference. The thing to remember with joins is that, so long as your table design is simple, just join "matching" items (e.g. a primary key with a foreign key) and then trim your SELECT columns to what you need.

    I've made a live forkable demo.

    0 讨论(0)
提交回复
热议问题