1

我有一些表大致如下:

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),
]

我试过的:

因为我习惯使用 ORM,所以我对 SQL 的理解很薄弱。我无法理解正常检索Employees链接到计算诅咒词的方式。这是我所做的(善良!):

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

我有一种感觉,我在这里严重误解了一些东西,所以如果有人能提供一个如何成功解决这个问题的例子,我会很感激一些指示。

4

2 回答 2

3

您想对加入表的结果进行分组:

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
于 2012-07-03T22:03:17.827 回答
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确实存在。

于 2012-07-03T22:05:39.313 回答