我有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
当我尝试链接所有者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
和其他数据
你看到的比订单错了。所以我的问题是如何保存该命令?
答案 0 :(得分:2)
取代subquery
使用join
。试试这个。
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
答案 1 :(得分:1)
解开这个烂摊子。首先聚合,稍后加入:
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
右侧是 集 ,忽略了元素的顺序,因此ORDER BY
毫无意义subuery。