[英]Postgres Nested Query and keeps the order
I have two queries and want to combine into one.我有两个查询,想合并为一个。
Query 1(Pseudocode):查询1(伪代码):
recipe_titles = select recipe_title
from recipe
where nutrient_id in (4,5)
group by recipe_title
order by sum(nutrient_amount) desc
Then, I want to use each recipe_title
to select the whole recipe row:然后,我想将每个
recipe_title
用于 select 整个配方行:
Query 2(Pseudocode):查询 2(伪代码):
select * from recipe where recipe_title = recipe_titles[n]. (n is 1, then 2, then 3...)
If the first query returns 100 recipe_title
, I will have to run the second query for 100 times, which is not efficient.如果第一个查询返回 100
recipe_title
,我将不得不运行第二个查询 100 次,效率不高。
Is there a way to do these two selection in a single query?有没有办法在一个查询中进行这两个选择?
IN
will not work for my case since the order is lost:由于订单丢失,
IN
不适用于我的情况:
select * from recipe where recipe_title in recipe_titles. (Not work)
You can use window functions.您可以使用 window 函数。 I would recommend a window conditional window
sum()
, that you can then use for filtering and ordering:我会推荐一个 window 有条件的 window
sum()
,然后您可以将其用于过滤和排序:
select *
from (
select
r.*,
sum(nutrient_amount)
filter(where nutrient_id in (4,5))
over(partition by recipe_title) as sum_nutrient_amount
from recipe r
) t
where sum_nutrient_amount > 0
order by sum_nutrient_amount desc, recipe_title, nutrient_id
On the other hand, if you don't need to filter on recipe_title
s that have either nutrient_id
4
or 5
, then the subquery is not necessary:另一方面,如果您不需要过滤具有
nutrient_id
4
或5
的recipe_title
,则不需要子查询:
select r.*
from recipe r
order by
sum(nutrient_amount)
filter(where nutrient_id in (4,5))
over(partition by recipe_title) desc,
recipe_title,
nutrient_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.