如何在pdo查询中进行内部选择?

时间:2017-12-09 06:58:15

标签: mysql pdo

我不确定如何确切地说明这个问题,因为我无法获得更好的标题,所以我无法搜索可能之前提出的相同问题。

我的数据库中有一对多关系,数据分布在几个表中。

public function get_recipe_data($id){
    $sth = $this->db->prepare('SELECT * FROM
                               recipe as recipe
                               LEFT JOIN recipe_introduction as introduction
                               ON recipe.id = introduction.recipe_id
                               LEFT JOIN recipe_ingredients as ingredients
                               ON recipe.id = ingredients.recipe_id
                               LEFT JOIN recipe_ingredients_notes as notes
                               ON recipe.id = notes.recipe_id
                               LEFT JOIN recipe_macros as macros
                               ON recipe.id = macros.recipe_id
                               WHERE recipe.id = :id
    ');
    $sth->bindValue(':id', $id, PDO::PARAM_INT);
    $sth->execute();

    return $sth->fetch(PDO::FETCH_ASSOC);
}

public function convertCategoryId($category_id){
    $sth = $this->db->prepare('SELECT name FROM recipe_categories WHERE id = :category_id');
    $sth->bindValue(':category_id', $category_id, PDO::PARAM_INT);
    $sth->execute();

    return $sth->fetch(PDO::FETCH_ASSOC);
}

在配方表中,有一个列具有类别名称的id,并引用另一个表。

食谱表

+----+-------+-------------+
| id | title | category_id |
+--------------------------+
| 1  |  ...  |      1      |
+----+-------+-------------+
| 2  |  ...  |      3      |
+----+-------+-------------+

我有另一张桌子

recipe_categories

+----+------------+
| id |    name    |
+----+------------+
| 1  |  breakfast |
+----+------------+
| 2  |    lunch   |
+----+------------+
| 3  |   dinner   |
+----+------------+
| .. |    ...     |
+----+------------+

现在我必须从上面的第一个查询返回结果,然后一旦我有了,我在类中运行另一个方法从第一个查询传递category_id,然后将它与recipe_categories匹配,但是这太低效了。

有没有办法让我能够直接从第一个查询中选择名称?

1 个答案:

答案 0 :(得分:0)

只需将类别表加入配方表,即可在单个查询中访问Categroty名称。

SELECT
      *
FROM recipe AS recipe
INNER JOIN recipe_categories AS rcat ON recipe.category_id = rcat.id
LEFT JOIN recipe_introduction AS introduction ON recipe.id = introduction.recipe_id
LEFT JOIN recipe_ingredients AS ingredients ON recipe.id = ingredients.recipe_id
LEFT JOIN recipe_ingredients_notes AS notes ON recipe.id = notes.recipe_id
LEFT JOIN recipe_macros AS macros ON recipe.id = macros.recipe_id
WHERE recipe.id = id

请注意。虽然PHP用户通常习惯使用"选择*"最佳做法是,您应该指定要返回的每一列,而不是让它成为偶然。