简体   繁体   English

PHP / MYSQL是否需要SQL加入?

[英]PHP / MYSQL Do I Need to SQL Join?

I know this may be a stupid question but I am not very experienced with SQL Joins and I don't want to do it without fully knowing that it is the right thing to do. 我知道这可能是一个愚蠢的问题,但是我对SQL Join的经验不是很丰富,并且在不完全知道这是正确的事情的情况下我不想这样做。

I have created a recipe site which have different categories like bread, biscuits, cake etc. these are all in the category table of the database. 我创建了一个食谱站点,该站点具有不同的类别,例如面包,饼干,蛋糕等。这些都在数据库的类别表中。 I have recipes in the recipe table. 我在食谱表中有食谱。

The problem I am facing is, on the category page, since each category has its own ID I created one page where each categories redirect to and used this code 我面临的问题是,在类别页面上,因为每个类别都有自己的ID,所以我创建了一个页面,每个类别都重定向到该页面并使用了此代码

<a href="index.php?p=selected&id=<?php echo $recipe['cat_id']; ?>">

This one page features different categories based on the ID, the id is changed in the url so for the bread category it would look like this: 此页面根据ID具有不同的类别,在URL中更改了ID,因此对于面包类别,它看起来像这样:

index.php?p=selected&id=1 的index.php?P =选择&ID = 1

So, since there is one page for each category I want it to display the recipes, I used this code: 因此,由于每个类别都有一个页面,我希望它显示食谱,因此我使用了以下代码:

$query = "SELECT * FROM recipes ORDER BY recipe_id ASC";

but this displays every recipe in the database, what I want is for it to display the recipe based on the category it is in like below: 但这会显示数据库中的每个配方,我想要的是根据它所在的类别显示配方,如下所示:

$query = "SELECT * FROM recipes WHERE cat_id = :id ORDER BY recipe_id ASC";

The cat_id is part of the category table, so do I need to join this table to the recipe table to make it work? cat_id是类别表的一部分,因此我需要将该表加入配方表以使其起作用吗?

Be sure to tell me if I have missed something, 一定要告诉我我是否错过任何事情,

Thank you for your time. 感谢您的时间。

yes you have missed something must add column cat_id in recipes table which equal cat_id in category table when you add item in recipes table and then it simple 是的,您错过了一些事情,当您在食谱表中添加项目时,必须在食谱表中添加列cat_id等于类别表中的cat_id,然后再简单

$query = "SELECT * FROM recipes
WHERE recipes.cat_id = :id";

or 要么

$id = intval($_GET['id']);
$query = "SELECT * FROM recipes
WHERE recipes.cat_id = $id";

If one recipe one category then, 如果一个食谱属于一种类别,

SELECT * FROM recipes inner join category
on category.id=recipe.cat_id
 where cat_id = :id ORDER BY recipe_id ASC";

If one cateory many recipes then 如果一个类别有很多食谱,那么

 SELECT * FROM recipes leftjoin category
    on category.id=recipe.cat_id
     where cat_id = :id ORDER BY recipe_id ASC";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM