1

我有emails_accounts一个结构如下的表:

╔════╦═════════════════════╦══════════════╗
║ id ║        email        ║ description  ║
╠════╬═════════════════════╬══════════════╣
║  1 ║ test@gmail.com      ║ Lorem        ║
║  2 ║ example@example.com ║ Ipsum        ║
║  3 ║ test@example.com    ║ Dolor        ║
║  4 ║ retail@example.com  ║ Sit Amet     ║
╚════╩═════════════════════╩══════════════╝

每封电子邮件都是独一无二的

第二个表email_templates的结构与此类似:

╔════╦══════════════════╦════════════╦══════════╗
║ id ║ email_title      ║ email_from ║ email_to ║
╠════╬══════════════════╬════════════╬══════════╣
║ 1  ║ Test title       ║ 1          ║ 3        ║
║ 2  ║ Second title     ║ 2          ║ 3        ║
║ 3  ║ Some title       ║ 1          ║ 1        ║
╚════╩══════════════════╩════════════╩══════════╝

email_to并且email_from可以不同,但​​它们可以相同(如示例中所示)。

我想要实现的是创建一个 SQL 查询,它为我提供表中的所有帐户,emails_accounts但还有其他信息 - 每个帐户在表中使用了多少email_templates(它需要检查email_fromemail_to)。

我知道这不应该太难,但到目前为止我还没有设法得到正确的结果。我目前的代码是:

SELECT acc.* , COUNT( temp.id ) 
FROM emails_accounts acc
LEFT JOIN email_templates temp ON acc.id = temp.email_from
GROUP BY acc.email

但我想两者email_from兼而有之email_to

我也试过这个:

SELECT acc . * , COUNT( temp.id ) + COUNT( temp2.id ) AS count
FROM emails_accounts acc
LEFT JOIN email_templates temp ON acc.id = temp.email_from
LEFT JOIN email_templates temp2 ON acc.id = temp2.email_to
GROUP BY acc.email

但它给出了太多的结果。


编辑:我创建了一个包含正确答案的小提琴 - 感谢jaczes

4

2 回答 2

1

那个怎么样 ?

SELECT ea.*,efrom, eto, ifnull(efrom,0)+ifnull(eto,0) as count 
from emails_accounts ea 
LEFT JOIN 
(select email_from,count(email_from) as efrom 
  FROM email_templates group by email_from)
as e_from on ea.id=email_from
LEFT JOIN 
(select email_to, count(email_to) as eto 
  FROM email_templates group by email_to)
as e_to on ea.id=email_to
于 2013-09-11T12:44:17.397 回答
0

在您的第一个查询中使用以下 UNION 作为虚拟表

select  email_from  as email_id
        ,Count(*)   as template_count
from    email_templates
group by
        email_from
union        
select  email_to    as email_id
        ,Count(*)   as template_count
from    email_templates
group by
        email_to
于 2013-09-11T12:27:46.020 回答