【问题标题】:Find recipe by ingredient name, and sort if possiple按成分名称查找食谱,并对其进行排序
【发布时间】:2017-05-21 19:32:42
【问题描述】:

我在为我的数据库编写查询时遇到问题。我在这里找到了许多类似的示例,并且已经尝试了好几个小时,但是没有一个示例可以帮助我弄清楚如何获得我想要的结果。我正在构建一个食谱应用程序,但我对与数据库有关的一切都很陌生。
我想挑选 1 种或更多 成分并获得匹配的食谱标题,如果可能,按最佳结果排序(包含最多成分的食谱)。 我尝试进行内部连接,尝试将食谱名称与匹配的成分结合在一起。

我已经尝试像这个人在这个问题中所做的那样做,因为我们有相同的设计: Recipe Database, search by ingredient

但即使我尝试像他/她那样加入,只是为了测试(而不是我想要的)它我得到:

ERROR:  missing FROM-clause entry for table

这是我的桌子:

配方_成分

+-----------+---------------+
| recipe_id | ingredient_id |
+-----------+---------------+
|         1 |             1 |
|         1 |             2 |
|         1 |             3 |
|         1 |             4 |
|         1 |             5 |
|         1 |             6 |
|         1 |             7 |   
|         2 |             1 |
|         2 |             8 |
|         2 |             9 |
|         2 |            10 |
|         2 |            11 |
+-----------+---------------+

食谱

+-----------+-----------------------+--------------+
|       id  | name                  | instructions |
+-----------+-----------------------+--------------+
|         1 | Guacamole             | sample text  |
|         2 | Grilled avocado toast | sample text  |
+-----------+-----------------------+--------------+

成分

+------------------+
| id | name        |
+----+-------------+
|  1 | avocado     |
|  2 | tomato      |
|  3 | chili       |
|  4 | garlic      |
|  5 | lemon       |
|  6 | salt        |
|  7 | black pepper|
|  8 | pesto       |
|  9 | spinach     |
| 10 | hard cheese |
| 11 | bread       |
+------------------+

sql

create table Recipe (
id SERIAL PRIMARY KEY,
name CHAR(50),
prep_time CHAR(10),
instructions VARCHAR(2000));

create table Ingredient (
id SERIAL PRIMARY KEY,
name CHAR(50));

create table Recipe_Ingredient (
recipe_id INT NOT NULL,
ingredient_id INT NOT NULL,
FOREIGN KEY(recipe_id) REFERENCES Recipe(id),
FOREIGN KEY(ingredient_id) REFERENCES Ingredient(id));

【问题讨论】:

  • 欢迎来到 Stack Overflow。请包括您已经尝试过的事情。你可以edit你的问题。
  • @simbabque 谢谢!已编辑:)
  • 请复制并粘贴您当前的查询,

标签: sql database postgresql


【解决方案1】:

您是否正在寻找这样的查询:

with cte as (
select recipe_id, count(*) as cnt from Recipe_Ingredient
group by recipe_id
) select r.id as Recipeid, r.name, c.cnt from Recipe r join cte c
    on r.id = c.recipe_id
    order by c.cnt desc

【讨论】:

  • 是的!谢谢!但是,如果我想搜索鳄梨和面包并获得“鳄梨吐司”作为第一个结果,因为它包含大部分成分,我该怎么写?
  • 想通了!谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-14
  • 1970-01-01
相关资源
最近更新 更多