开发者社区> 问答> 正文

如何在关系表的同一列中获取具有两个结果的项目

我有一个食谱数据库,其中包含午餐,晚餐,甜点,无糖等类别,并且我想返回例如无糖和甜点的食谱。

我的表的图像,因为SO不能很好地处理表

Recipes |---------------------|------------------| | id | name | |---------------------|------------------| | 12 | cookies | |---------------------|------------------| | 15 | spaghetti | |---------------------|------------------| | 22 | sugar-free tarts | |---------------------|------------------|

Categories |---------------------|------------------| | id | name | |---------------------|------------------| | 1 | dinner | |---------------------|------------------| | 2 | dessert | |---------------------|------------------| | 3 | sugar free | |---------------------|------------------|

Recipe Categories

idrecipe_idcategory_id
------------------------------------------------------------
1122
------------------------------------------------------------
2151
------------------------------------------------------------
3153
------------------------------------------------------------
4222
------------------------------------------------------------
5223
------------------------------------------------------------

我尝试使用此查询,但是我得到的只是甜点或无糖配方(如果使用示例图像数据,则返回意大利面)

SELECT r.* FROM recipes r JOIN recipe_categories rc ON r.id = rc.recipe_id WHERE rc.category_id ='2' OR rc.category_id ='3' GROUP BY recipe_id HAVING COUNT(rc.id)>=2 ORDER BY r.created_on DESC 问题演示:https : //www.db-fiddle.com/f/22WF9LtaUKjzzU6d9S4ALH/3

问题来源于stack overflow

展开
收起
保持可爱mmm 2019-11-15 11:52:07 558 0
1 条回答
写回答
取消 提交回答
  • 这样可以:

    SELECT r.id, r.name FROM recipes r JOIN recipe_categories rc ON r.id = rc.recipe_id WHERE rc.recipe_category_name_id ='2' OR rc.recipe_category_name_id ='3' GROUP BY r.id, r.name HAVING COUNT(DISTINCT rc.recipe_category_name_id) = 2 参见演示。 结果:

    idname
    22sugar-free tarts
    2019-11-15 11:56:31
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
RowKey与索引设计:技巧与案例分析 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载