有没有更优雅的方法来查询多个OR和AND上的多对多表?

药丸:

我有桌子dishesingredientsdishes_ingredients我想展示所有带有mango和的菜肴chicken我可以通过首先获取所有包含的菜肴mango,然后选择chicken这些结果中也包含的所有菜肴来实现像这样:

SELECT e_dishes.id, e_dishes.name FROM 
(
 SELECT DISTINCT dishes.id, dishes.name FROM dishes 
 JOIN dishes_ingredients ON dishes.id = dishes_ingredients.dishes_id 
 JOIN ingredients ON dishes_ingredients.ingredients_id = ingredients.id 
 WHERE ingredients.name = 'mango'
) AS e_dishes
JOIN dishes_ingredients ON e_dishes.id = dishes_ingredients.dishes_id
JOIN ingredients ON dishes_ingredients.ingredients_id = ingredients.id
WHERE ingredients.name = 'chicken';

但这似乎还不够优雅。我认为,必须有一种方式来获得一个包含所有菜肴mango,并chicken在短短的一个查询。

戈登·利诺夫(Gordon Linoff):

您可以使用聚合:

SELECT  d.id, d.name
FROM dishes d JOIN
     dishes_ingredients di
     ON d.id = di.dishes_id JOIn
     ingredients i
     ON di.ingredients_id = i.id 
WHERE i.name IN ('mango', 'chicken')
GROUP BY d.id, d.name
HAVING COUNT(*) = 2;  -- number of ingredients

假设没有列出相同的成分两次。如果是这样,请使用having count(distinct i.name) = 2

请注意使用表别名,因此查询更易于编写和阅读。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

有没有更优雅的方法来折叠 dplyr 中的两行?

有没有更优雅的方法来检查表单默认值?

有没有更优雅的方法来检查freemarker中的变量?

Vue.js-有没有更优雅的方法来有条件地应用类?

有没有更优雅的方法来编写带有重叠(嵌套)替代方案的语句?

有没有更有效/更优雅的方法来从开关案例中的功能更改数据?

有没有更好,更优化的方法来执行此SQL查询?

有没有更优雅的方法来输入映射作为 Clojure 中 stdin 中的对列表?

有没有更优雅的方法来过滤函数的失败结果?

有没有更好或更优雅的方法来处理python中的字典循环异常?

有没有一种更优雅的方式来代替编写大量查询?

有没有更好或更优雅的方法来在React Native中有条件地渲染不同的组件?

有没有更好/更干净/更优雅的方式来分配和释放cuda?

有没有更优雅的子串方法?

有没有更好或更优雅的方法来找出实际显示器的有效像素尺寸?

有没有更优雅的方式?

有没有一种优雅的方法来迭代索引和熊猫数据框的一列?

有没有更简洁/优雅的方法来根据其内容查找和选择特定的ComboBoxItem?

有没有更优雅的方法来使用 array.map 在 NodeJS 中解决这个问题?

有没有更优雅的方法来用默认字符串解开Option <Cookie>?

有没有简单优雅的方法来定义单例?

有没有一种优雅的方法来避免 Promise 的代码重复?

有没有更多的Pythonic /优雅方法来扩展Numpy数组的尺寸?

有没有简单/优雅的方法来将整数范围推入STD向量?

有没有没有查询字符串的方法来获取URL?

在 Kotlin 中是否有更优雅的方法来检查 String 是否是有效的 Int?

有没有更优雅的方式来重复使用代码块?

有没有更优雅的方式来启动基于列表的线程?

有没有更优雅的方式来执行这个 switch 语句?