执行 SQL 查询以在多对多关系中按成分 ID 获取鸡尾酒

我需要帮助创建一个 SQL 查询,该查询将从数据库返回鸡尾酒,因为我已经提供了进入该鸡尾酒的所有成分


因此,例如,我希望“Gin and Tonic”行仅在我为 Gin(id 为 1)和 Tonic(id 为 2)提供正确的 id 时返回。我只提供“补品”,我不应该回到这一行


我正在使用 SQLAlchemy 和 Flask,但我仍然无法理解查询将如何工作


这是我的表结构的样子


+-------------------+

| Tables_in_my_database |

+-------------------+

| cocktails         |

| ing_in_cocktails  |

| ingredients       |

+-------------------+

这是我的鸡尾酒桌


+----+----------------+-------+---------+

| id | name           | glass | finish  |

+----+----------------+-------+---------+

|  1 | white russisan | rocks | stirred |

|  2 | gin and tonic  | rocks | stirred |

+----+----------------+-------+---------+

这是我的配料表


+----+---------+----------+

| id | name    | ing_type |

+----+---------+----------+

|  1 | vodka   | fruit    |

|  2 | kahluha | fruit    |

|  3 | gin     | fruit    |

|  4 | tonic   | fruit    |

+----+---------+----------+

这是我的关系表


+----+-------------+--------+

| id | cocktail_id | ing_id |

+----+-------------+--------+

|  1 |           1 |      1 |

|  2 |           1 |      2 |

|  3 |           2 |      3 |

|  4 |           2 |      4 |

+----+-------------+--------+

以下是对应的 SQLAlchemy 模型


class Cocktail(db.Model):

    __tablename__ = 'cocktails'

    id = db.Column(db.Integer, primary_key=True)

    name = db.Column(db.String(80), nullable=False)

    glass = db.Column(db.String(20), nullable=False)

    finish = db.Column(db.String(20), nullable=True)

    ingredients = db.relationship(

        'Ingredient',

        secondary=ing_in_cocktails,

        backref=db.backref('cocktails', lazy='dynamic')

    )


class Ingredient(db.Model):

    __tablename__ = 'ingredients'

    id = db.Column(db.Integer, primary_key=True)

    name = db.Column(db.String(80), nullable=False)

    ing_type = db.Column(db.String(20), nullable=False)



ing_in_cocktails = db.Table(

    'ing_in_cocktails',

    db.Column('id', db.Integer, primary_key=True),

    db.Column('cocktail_id', db.Integer, db.ForeignKey('cocktails.id')),

    db.Column('ing_id', db.Integer, db.ForeignKey('ingredients.id'))

)



江户川乱折腾
浏览 228回答 3
3回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python