簡體   English   中英

單個表的 Postgres 嵌套查詢

[英]Postgres Nested Query for a single table

我被困在一個嵌套的數據庫查詢上。 我能得到一些幫助嗎?

我的簡單表如下所示:

食物表:

+----+----------+-------------------------------+
| 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
         .............

我想 select 前 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    

這很棘手。 您可以使用GROUP BY來執行此操作:

select name
from food_table
where Nutrient in ('calcium', 'magnesium' )
group by name
order by max(NutrientAmount) desc 
limit 15;

如果您想同時考慮這兩種營養素,您將使用sum()而不是max()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM