在 postgres 中,如何在不选择该字段的情况下对 string_agg 函数的结果值进行排序?子查询不可能

In postgres, how to sort on, among others, a result value of a string_agg function, without selecting that field? Subquery not possible

我有这个查询(已经简化但实际上更复杂):

SELECT
    e.id,
    string_agg(csb.description, ',' ORDER BY cs.id ASC) AS condition_set_descriptions
FROM event e
JOIN event_trigger_version etv ON e.event_trigger_version_id = etv.id
LEFT JOIN event_condition_set ecs ON ecs.event_id = e.id
JOIN condition_set cs ON cs.id = ecs.condition_set_id
JOIN condition_set_base csb ON cs.condition_set_base_id = csb.id
JOIN subject s ON e.subject_id = s.id
GROUP BY
    e.id, event_level, s.name
ORDER BY s.name ASC, condition_set_descriptions ASC, event_level DESC
LIMIT 20 OFFSET 0

现在我可以有一个动态 ORDER BY 也包括其他列(在本例中被省略),但总是在顺序中的某处包括 condition_set_descriptions。此列是 string_agg 函数的结果。我不能将其移动到子查询,因为设置的 LIMIT 应该应用于定义的 ORDER BY 列的 组合 的结果。

该示例运行良好,但缺点是 condition_set_descriptions 列也作为查询结果返回,但这是大量数据,实际上并不需要(因为实际描述是使用一些省略的数据以另一种方式查找)。所需要的只是对结果进行排序。如果不在会破坏多排序有限结果集的正确性的子查询中选择它,我该如何做到这一点?

ORDER BY 也可以用于计算表达式;不必是您在 SELECT 中计算某些内容然后在 ORDER BY

中别名和引用别名

看看在做什么:

SELECT
    e.id
FROM 
  ...
ORDER BY 
    s.name ASC,
    string_agg(csb.description, ',' ORDER BY cs.id ASC) ASC, 
    event_level DESC
LIMIT 20 OFFSET 0

还要仔细检查内部联接中间是否有左联接;当下一个 table 被内部连接到它时,它产生的任何空值都将被再次删除,因此您可以内部连接它,或者如果您正在丢失数据,则采用以下模式:

w
JOIN x
LEFT JOIN (
  y
  JOIN z
) a

即不要左连接 y 到 x 然后内连接 z 到 y,先内连接 y 和 z 然后左连接结果到 x