具有多个连接的复杂SQL

时间:2015-06-15 14:06:16

标签: mysql database join

我有一个政治家,政党和选举候选人的候选人数据库。该数据库由以下表格组成:人员,组,候选人和职位。 Candidacies表是人员和组之间的连接关系。 Candidacies表中的每个记录代表选举中的候选人,并且与特定帖子(帖子表中的记录)相关联。每个帖子都有PostTypes表中的帖子类型(参议员,总统等),并链接到一个选区,在这种情况下,从一个表(部门)中抽取的10个部门(如州)之一。

所以,我有:

表:人; PK:id 表:组; PK:id 表:CANDIDACIES; PK:id,FKs:id_People,id_Groups,id_Posts 表:POSTTYPES; PH:id 表:POSTS; PK:id; FK:id_Department,id_PostTypes 表:部门; PK:id

我正在尝试创建一个SQL语句,该语句将选择特定帖子类型(id_PostType = X)的Candidacies总数,post是特定部门(id_Department = X)的特定帖子(id_Post = X)。

我在邮政选择时工作,但似乎无法让部门进一步选择。我想我可能需要做另一次加入或其他什么,但我迷路了。

这就是我所拥有的:

SELECT g.name, COUNT(c."id") AS theCount 
FROM Candidacies c 
    JOIN Groups g
        ON c."id_Groups" = g."id"
    JOIN People p
        ON c."id_People" = p."id"
    WHERE ( c."id_PostTypes" = "Senator" ) 
    GROUP BY g."name"
    ORDER BY theCount

这似乎是选择帖子类型为参议员的候选人姓名和总人数。我现在如何添加特定职位部门的标准?

2 个答案:

答案 0 :(得分:0)

Yes, you have to join the table which need informations,through the intermediate if required. But be carefull with the aggregate functions. If do not handling right you get total wrong results.

SELECT g.name, COUNT(c."id"), d.DepartmentName AS theCount 
FROM Candidacies c 
JOIN Groups g
    ON c."id_Groups" = g."id"
JOIN People p
    ON c."id_People" = p."id"
JOIN PostTypes pt
    ON c."id_PostTypes" = pt."id" /*?*/
JOIN Departments  d
    ON pt.Id_Department=d.id /* suppost are these the names*/
WHERE ( c."id_PostTypes" = "Senator" ) 
GROUP BY g."name", d.DepartmantName
ORDER BY COUNT(c."id")

答案 1 :(得分:0)

What I think you should take note of here is that each post has a department and a postType. If you take a step back, you can select all posts that belong to a certain department and a certain postType like this:

SELECT p.*
FROM posts p
JOIN department d ON d.id = p.id_department AND d.name = 'Department1'
JOIN postTypes pt ON pt.id = p.id_postTypes AND pt.name = 'Senator';

Now that you have all of those posts, you can also join the candidacies table, and GROUP BY each group, which is what your question implies you want:

SELECT c.id_groups, COUNT(*) AS numCandidacies
FROM candidacies c
JOIN posts p ON p.id = c.id_posts
JOIN department d ON d.id = p.id_department AND d.name = 'Department1'
JOIN postTypes pt ON pt.id = p.id_postTypes AND pt.name = 'Senator'
GROUP BY c.id_groups;