1

目前我可以从配方表中提取配方名称,但我希望能够从配料表中获取所需的配料。我知道这与 JOINS 有关,但我是 JOINS 的新手。

这是成分表 这是成分表

这是 recipeingredients 表,它有两个主键,所以我可以将多种成分分配给一个食谱 这是 recipeingredients 表,它有两个主键,所以我可以将多种成分分配给一个食谱

这是食谱表 这是食谱表

这是搜索脚本

<?php
    $query = $_GET['query'];
    // gets value sent over search form

    $min_length = 3;


    if(strlen($query) >= $min_length){ 

        $query = htmlspecialchars($query);


        $query = mysql_real_escape_string($query);
        // makes sure nobody uses SQL injection

        $raw_results = mysql_query("SELECT * FROM recipes
            WHERE (`recipename` LIKE '%".$query."%') OR (`ingredients` LIKE '%".$query."%')") or die(mysql_error());





        if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following

            while($results = mysql_fetch_array($raw_results)){
            // $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop

                echo "<p>Recipe:".$results['recipename']."</p><p>Ingredients:".$results['ingredients']."<p>Instructions:".$results['instructions']."</p>";
                // posts results gotten from database(title and text) you can also show id ($results['id'])
            }

        }
        else{ // if there is no matching rows do following
            echo "No results";
        }

    }
    else{ // if query length is less than minimum
        echo "Minimum length is ".$min_length;
    }
?>

成分样本数据

在此处输入图像描述

配方成分样本数据

在此处输入图像描述

配方表样本数据

在此处输入图像描述

4

1 回答 1

1
SELECT
    r.*,
    i.*
FROM recipe AS r
INNER JOIN recipeingredients AS ri
    ON ri.recipeid = r.recipeid
INNER JOIN  ingredients AS i
    ON i.ingredientid = ri.ingredientid
WHERE r.recipename = 'Beans On Toast'

这将为您提供食谱及其成分。

编辑

这是你如何做到的。

$query  ="  SELECT
                r.*,
                i.*
            FROM recipe AS r
            INNER JOIN recipeingredients AS ri
                ON ri.recipeid = r.recipeid
            INNER JOIN  ingredients AS i
                ON i.ingredientid = ri.ingredientid
            WHERE r.recipename = 'Beans On Toast'";

$raw_results = mysqli_query($query) or die(mysqli_error()); 
于 2013-05-02T19:20:28.053 回答