首页 > 解决方案 > 单个表的 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,但它不起作用,因为它是为了订购一列。我要排序的数据存储在不同的行中。

我是数据库设计的新手。如果架构有问题,我也要更改架构。

标签: sqlpostgresql

解决方案


您可以尝试使用 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    

推荐阅读