按嵌套 table 计数排序

Ordering by a nested table count

我有两个 tables Major(majorId, label)Minor(minorId, majorId).

我想要 return Major 按 Minor 的计数(和标签)排序。

类似于:

SELECT majorId,
       label
FROM Major ma
ORDER BY
  (SELECT COUNT(*)
   FROM Minor mi
   WHERE mi.majorId=ma.majorId), label;

我想象它的工作方式是:Minor table 按 majorId 分组,然后为每个 majorId 计算行数,然后 Major table 按相应计数排序,然后按标签。

这个怎么样:

SELECT majorId, label
FROM Major ma
ORDER BY (SELECT COUNT(*) FROM Minor mi WHERE mi.majorId=ma.majorId 
group by mi.majorId), label ;

除了分组,您还可以使用 lateral-join:

SELECT majorId, label
    ,tMinor.cnt 
FROM Major AS ma 
LATERAL
(
     SELECT COUNT(*) AS cnt 
     FROM Minor AS mi 
     WHERE mi.majorId = ma.majorId
) AS tMinor 

ORDER BY cnt, label

或传统上与组:

SELECT 
     majorId, label
    ,COUNT(DISTINCT mi.minorId) AS cnt 
FROM Major AS ma 

LEFT JOIN Minor AS mi 
     ON mi.majorId = ma.majorId

GROUP BY majorId, label

ORDER BY cnt, label