sql - 单个表的 Postgres 嵌套查询
问题描述
我被困在一个嵌套的数据库查询上。我能得到一些帮助吗?
我的简单表如下所示:
食物表:
+----+----------+-------------------------------+
| ID | NAME | Nutrient | NutrientAmount
+----+----------+---------------+---------------+
food1 calcium 200
food1 magnesium 300
food1 phosphorus 400
food2 calcium 220
food2 magnesium 320
food2 phosphorus 430
food3 calcium 230
.............
我想选择钙和镁含量最高的 15 种食物。钙或镁含量最多并不重要。
我尝试使用order by
,但它不起作用,因为它是为了订购一列。我要排序的数据存储在不同的行中。
我是数据库设计的新手。如果架构有问题,我也要更改架构。
解决方案
您可以尝试使用 distinct
select distinct NAME
from food_table
where Nutrient in ('calcium', 'magnesium' )
order by NutrientAmount DESC
LIMIT 15
或者为了避免明显的限制问题,您可以尝试使用
select distinct t.name
from (
select NAME
from food_table
where Nutrient in ('calcium', 'magnesium' )
order by NutrientAmount DESC
) t
LIMIT 15
推荐阅读
- java - 日期选择器硒
- ruby - 从 Process.spawn 获取正确的 PID
- javascript - 如何将excelsheet行高设置为自动,以便内容可以使用exceljs自动适应单元格
- java - 为数组中的索引赋值
- ios - 如何以编程方式获取当前正在运行的 XC 测试计划的配置?
- python - 未找到 libtorrent 模块
- python - ValueError:int() 的无效文字,基数为 10:'string'
- batch-file - 在批处理字符串中使用特殊字符
- python - 根据医疗保险费用绘制 bmi
- microsoft-teams - 尝试获取团队/频道聊天中共享的附件的 SharePoint 文件的可下载 URL