2012-07-03 38 views
1

我有一些表格大致是这么一个SUM:执行了嵌套的外键关系

Client: 
    id 
    name 

Employee 
    id 
    name 

Email 
    id 
    to : Client [ForeignKey] 
    from : Employee [ForeignKey] 

EmailStats (Tracks the stats for a particular single email) 
    id 
    email : Email [OneToOne] 
    curse_words : 10 

我想要做什么:我想获取已经写至少一个电子邮件的所有员工单个客户,用的次数沿着他们诅咒他们的任何电子邮件到单一的客户端,即特定的Client回报

[ 
    ('name' : 'Paul', 'total_curses' : 255), 
    ('name' : 'Mary', 'total_curses' : 10), 
] 

我试过的东西:

我对SQL的理解相当薄弱,因为我习惯于使用ORM。我无法理解如何正常检索链接到计数诅咒词的链接。下面是我做了什么(是那种!):

SELECT DISTINCT (
    SELECT SUM(EmailStats.curse_words) 
    FROM EmailStats 
    INNER JOIN (
     SELECT Email.id 
     FROM Email 
     INNER JOIN Employee 
      ON Email.from = Employee.id 
     WHERE Email.to = 5 // Assuming 5 is the client's id 
    ) filtered_emails ON EmailStats.email = filtered_emails.id     
) AS 'total_curses', Employee.name 
FROM Employee 
INNER JOIN Email 
    ON Email.from = Employee.id 
WHERE Email.to = 5 // Assuming 5 is the client's id 
ORDER_BY 'total_curses' 

这是行不通的 - 这似乎获取正确Employees(那些谁发送到Client),但诅咒数似乎总为所有电子邮件Client,而不是那些诅咒Employee

我有一种感觉,我在这里严重误解了一些东西,所以如果任何人都可以提供一个如何成功的例子,我会欣赏一些指针。

+1

没有建设性,但你为什么样的公司工作?嘲笑你的客户?大声笑! – SuperMykEl

回答

2

你要入组的表的结果:

SELECT Employee.name, SUM(EmailStats.curse_words) total_curses 
FROM  Email 
    JOIN EmailStats ON EmailStats.email = Email.id 
    JOIN Employee ON Employee.id  = Email.from 
WHERE Email.to = 5 
GROUP BY Employee.id 
ORDER BY total_curses DESC 
2
SELECT em.name, sum(s.curse_words) AS total_curses 
FROM employee em 
JOIN email e ON e.from = em.id 
LEFT JOIN emailstats s ON s.email = e.id 
WHERE e.to = $the_one_client 
GROUP BY em.name 
ORDER BY total_curses DESC; 

我使用LEFT JOIN以确保,因为似乎没有要保证,在emailstats有匹配的行实际上存在。