2012-07-03 60 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有匹配的行實際上存在。