SQL:如何在 sql 查询中保存顺序?

SQL: How to save order in sql query?

我有 PostgreSQL 数据库,我尝试打印我的所有用户(人)。

当我执行这个查询时

-- show owners 
-- sorted by maximum cars amount
SELECT p.id
  FROM car c JOIN person p ON c.person_id = p.id
  GROUP BY p.id
  ORDER BY COUNT(p.name) ASC;

我让所有车主按汽车数量排序

输出:3 2 4 1

当我尝试 link 所有者 ID 时,所有订单都出错了。

SELECT *
FROM person p
WHERE p.id IN (
  SELECT p.id
  FROM car c JOIN person p ON c.person_id = p.id
  GROUP BY p.id
  ORDER BY COUNT(p.name) ASC);

输出:1 2 3 4和其他数据

你看不是顺序错了。那么我的问题是如何保存该订单?

使用 join 而不是 subquery。试试这个。

SELECT p.*
FROM   person p
       JOIN (SELECT p.id,
                    Count(p.NAME)cnt
             FROM   car c
                    JOIN person p
                      ON c.person_id = p.id
             GROUP  BY p.id) b
         ON p.id = b.id
ORDER  BY cnt ASC 

解开混乱。先聚合,后加入:

SELECT p.*
FROM   person p
JOIN  (
   SELECT person_id, count(*) AS ct
   FROM   car
   GROUP  BY person_id
   ) c ON c.person_id = p.id
ORDER  BY c.cnt;

无需加入 person 两次。如果您计算 大多数或所有行 .
,这应该是最快的 对于小选择相关子查询更快:

SELECT p.*
FROM   person p
ORDER  BY (SELECT count(*) FROM car c WHERE c.person_id = p.id)
WHERE  p.id BETWEEN 10 AND 20;  -- some very selective predicate

至于你原来的:IN在右边取一个set,元素的顺序被忽略了,所以ORDER BY在subuery中毫无意义。