检查另一个表是否使用了行

时间:2013-09-11 12:21:42

标签: mysql sql

我有一个表格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_toemail_from可以不同,但​​它们可以相同(如示例所示)。

我想要实现的是创建一个SQL查询,它从表emails_accounts中为我提供了所有帐户,但提供了其他信息 - 表格中使用了多少帐户{{ 1}}(需要检查email_templatesemail_from)。

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

email_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

但它产生了太多结果。


编辑:我created a fiddle包含正确答案 - 感谢jaczes

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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