我有一个像这样的数据库架构:
CREATE TABLE projects (project_id int);
CREATE TABLE project_members (user_id int, project_id int);
CREATE TABLE project_issues (issue_id int, project_id int);
我想要的是找到所有拥有10个或更多成员以及10个或更多问题的项目。我正在努力想出一个查询。
我希望输出类似于:
project_id | members | issues
-----------+---------+-------
65 | 100 | 23
93 | 78 | 45
最好按成员排序然后发布。
我想出了:
SELECT projects.project_id, COUNT(project_members.user_id) FROM
project_members LEFT JOIN projects ON
project_members.project_id = projects.project_id GROUP BY projects
ORDER BY count;
但不知道如何在计算问题时将其提升到新的水平。
我正在使用PostgreSQL 9.1
答案 0 :(得分:4)
有点简单&更快:
SELECT p.project_id, m.members, i.issues
FROM projects p
JOIN (
SELECT project_id, count(*) AS members
FROM project_members
GROUP BY project_id
HAVING count(*) >= 10
) m USING (project_id)
JOIN (
SELECT project_id, COUNT(*) AS issues
FROM project_issues
GROUP BY project_id
HAVING count(*) >= 10
) i USING (project_id)
ORDER BY m.members DESC, i.issues DESC;
既然你想要项目,
有10个或更多成员以及10个或更多个问题
..您可以通过JOIN
和HAVING
提前取消不符合资格的候选人,以获得更快的结果。
还有其他一些小调整。
并将>= 10
或> 9
设为“10或更多”!
警惕“代理交叉连接”:
Two SQL LEFT JOINS produce incorrect result
答案 1 :(得分:2)
这可能会更有效率,但它会给出正确的结果。
SELECT
p.project_id,
m.members,
i.issues
FROM projects AS p
LEFT JOIN
(
SELECT project_id, COUNT(user_id) AS members
FROM project_members
GROUP BY project_id
) AS m
ON p.project_id = m.project_id
LEFT JOIN
(
SELECT project_id, COUNT(issue_id) AS issues
FROM project_issues
GROUP BY project_id
) AS i
ON p.project_id = i.project_id
WHERE members > 10 AND issues > 10
ORDER BY members, issues;